第四讲 跳转结果的方式
1设置 ModelAndView对象,根据View的名称,和视图解析器跳转到指定的页面。
页面:试图解析器的前缀+view name +视图解析器的后缀
@Controllerpublic class HelloController { @RequestMapping("/hello") public ModelAndView hello(HttpServletRequest req,HttpServletResponse rep){ ModelAndView mv = new ModelAndView(); mv.addObject("msg", "hello Springmvc Annotation"); mv.setViewName("hello"); return mv; }
2通过ServletAPI对象来实现,不需要视图解析器
通过HttpServletResponse 来进行输出
@Controllerpublic class HelloController { @RequestMapping("/hello") public void hello(HttpServletRequest req,HttpServletResponse rep) throws IOException{ rep.getWriter().println("spring mvc user httpservletapi"); }
通过HttpServletResponse 实现重定向
@Controllerpublic class HelloController { @RequestMapping("/hello") public void hello(HttpServletRequest req,HttpServletResponse rep) throws IOException{ //rep.getWriter().println("spring mvc user httpservletapi"); //实现重定向 rep.sendRedirect("index.jsp"); }}
通过HttpServletRequest 实现转发
@Controllerpublic class HelloController { @RequestMapping("/hello") public void hello(HttpServletRequest req,HttpServletResponse rep) throws IOException, ServletException{ //rep.getWriter().println("spring mvc user httpservletapi"); //实现重定向 //rep.sendRedirect("index.jsp"); //实现转发 req.setAttribute("msg", "servlet api forward"); req.getRequestDispatcher("index.jsp").forward(req, rep); }}
3 通过springmvc来实现转发和重定向 没有视图解析器
转发的实现1
@RequestMapping("/hello1") public String hello(){ return "index.jsp"; }
转发的实现2
@RequestMapping("/hello1") public String hello(){ //转发1 //return "index.jsp"; //转发2 return "forward:index.jsp"; }
重定向
@RequestMapping("/hello1") public String hello(){ //转发1 //return "index.jsp"; //转发2 //return "forward:index.jsp"; return "redirect:index.jsp"; }
4 通过springmvc来实现转发和重定向--有视图解析器
转发
@RequestMapping("/hello2") public String hello2(){ return "hello"; }
注意:重定向return "redirect:index.jsp"不需要视图解析器
@RequestMapping("/hello2") public String hello2(){ //转发 //return "hello"; //重定向 return "redirect:hello.do"; }