一:設置ModelAndView對象,根據View的名稱,和視圖解析器跳轉到指定的頁面。
頁面:視圖解析器的前綴+view name +視圖解析器的後綴
<!-- 配置視圖渲染器 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!-- 將視圖名 渲染後視圖的前綴 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 渲染後視圖的後綴 -->
<property name="suffix" value=".jsp"/>
</bean>
@RequestMapping(value="/hello.do")
public ModelAndView hello(){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello");
mv.addObject("msg", "annotation ------");
return mv;
}
二:通過ServletAPI對象來實現。不需要視圖解析器的配置
通過HttpServletResponse輸入內容。
通過HttpServletResponse實現重定向,轉發。
public void hello(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
//內容輸出
resp.getWriter().println("hello springmvc");
//重定向
resp.sendRedirect("/jsp/hello.jsp");
//轉發
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
三:通過springmvc實現重定向和轉發(未配置視圖解析器)
@RequestMapping("/hello1.do")
public String hello1(ModelMap map){
//轉發
return "index.jsp";
}
@RequestMapping("/hello2.do")
public String hello2(ModelMap map){
return "forward:index.jsp";
}
@RequestMapping("/hello3.do")
public String hello3(ModelMap map){
map.addAttribute("msg", "helloworld");
return "redirect:/WEB-INF/jsp/hello.jsp";
}
四:通過springmvc實現重定向和轉發(配置視圖解析器)
@RequestMapping("/hello.do")
public String hello(ModelMap map){
//轉發
return "hello";
}
直接轉發至/WEB-INF/jsp/hello.jsp頁面。具體要看視圖解析器配置的前綴和後綴。
//重定向
@RequestMapping("/hello2.do")
public String hello2(ModelMap map){
//報錯示例1
return "redirect:hello";
//報錯示例2
return "redirect:hello.jsp";
//正解
return "redirect:hello.do";
}
頁面訪問hello2.do。發現跳轉至hello。因@RequestMapping註釋沒有hello。故報404錯誤。
這種重定向其實是跳轉至另一個.do。不會使用配置的視圖解析器。