#方式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"; }