#方式1:经过ModelAndView实现
设置ModelAndView对象,根据viewName和视图解析器跳转到指定的页面。
页面路径:视图解析器前缀+viewName+视图解析器后缀
ModelAndView设置以下web
@RequestMapping(value="/hello",method= RequestMethod.GET) public ModelAndView hello(HttpServletRequest req,HttpServletResponse resp){ ModelAndView mav = new ModelAndView(); //封装要显示的视图中的数据 mav.addObject("msg","hello springmvc"); //视图名,该视图是/WEB-INF/jsp/hello.jsp mav.setViewName("hello"); return mav; }
视图解析器以下spring
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean>
#方式2:经过ServletAPI实现,这个不须要配置视图解析器
经过HttpServletResponse来进行输出mvc
@RequestMapping(value="/hello",method= RequestMethod.GET) public void hello(HttpServletRequest req,HttpServletResponse resp) throws IOException{ resp.getWriter().println("hello mvc"); }
#方式3:经过HttpServletResponse来实现重定向app
@RequestMapping(value="/hello",method= RequestMethod.GET) public void hello(HttpServletRequest req,HttpServletResponse resp) throws IOException{ //HttpServletResponse输出 //resp.getWriter().println("hello mvc"); //HttpServletResponse重定向 resp.sendRedirect("index.jsp"); }
#方式4:经过HttpServletRequest转发jsp
@RequestMapping(value="/hello",method= RequestMethod.GET) public void hello(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException{ //HttpServletResponse输出 //resp.getWriter().println("hello mvc"); //HttpServletResponse重定向 //resp.sendRedirect("index.jsp"); //HttpServletRequest转发 req.setAttribute("msg", "显示内容"); req.getRequestDispatcher("index.jsp").forward(req, resp); }
#方式5:经过springmvc实现重定向与转发(没有视图解析器)
重定向与转发的区别
地址栏里的地址没有改变的话,是转发;改变了则是重定向。spa
@RequestMapping(value="/hello",method= RequestMethod.GET) public String hello(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException{ //转发方式1 //return "index.jsp"; //转发方式2 return "forward:index.jsp"; }
重定向code
@RequestMapping(value="/hello",method= RequestMethod.GET) public String hello(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException{ //转发方式1 //return "index.jsp"; //转发方式2 //return "forward:index.jsp"; //重定向(地址栏会改变) return "redirect:index.jsp"; }
#方式6:经过springmvc实现重定向与转发(有视图解析器)对象
@RequestMapping(value="/hello",method= RequestMethod.GET) public String hello(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException{ //转发方式1(有视图解析器) //return "hello"; //重定向(注意:重定向是不须要使用视图解析器的) return "redirect:index.jsp"; }