一:设置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。不会使用配置的视图解析器。