A return value classification:
- String: Returns the value of the view to be presented
- void: return to the default page (method name .jsp)
- ModleAndView: storage object and return to the Page Setup
1. String:
jsp:
1 <a href="/user/testString">response</a>
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <html> 3 <head> 4 <title>success</title> 5 </head> 6 <body> 7 <h3>执行成功</h3> 8 9 ${user.username} 10 ${user.age} 11 </body> 12 </html>
控制器方法:
/** * 返回值为需要展示的视图 * @param model * @return */ @RequestMapping("/testString") public String testString(Model model){ System.out.println("testString执行了..."); //模拟从数据库中查询出User对象 User user = new User(); user.setUsername("美美"); user.setPassword("123"); user.setAge(30); //设置model对象 model.addAttribute("user",user); return "success"; }
2.void
jsp:
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 3 <html> 4 <head> 5 <title>response</title> 6 </head> 7 <body> 8 9 <a href="/user/testString">testString</a> 10 <a href="/user/testVoid">testVoid</a> 11 </body> 12 </html>
方法:
1 /** 2 * void的返回值,会默认跳转到一个testVoid.jsp的页面下导致错误。 3 * 我们可以使用 4 * 1.请求转发:路径名为 "/WEB-INF/pages/success.jsp" 5 * 2.重定向:路径名为 request.getContextPath()+"/success.jsp" 6 * 7 * @param request 8 * @param response 9 * @throws Exception 10 */ 11 @RequestMapping("/testVoid") 12 public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception { 13 14 System.out.println("testVoid执行了..."); 15 16 //请求转发 17 // request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); 18 19 //重定向 20 // response.sendRedirect(request.getContextPath() + "/success.jsp"); 21 22 //直接响应 23 response.setCharacterEncoding("UTF-8"); 24 response.setContentType("text/html;charset=UTF-8"); 25 26 response.getWriter().println("hello"); 27 28 return; 29 }
3.ModelAndView
jsp
1 <a href="/user/testModelAndView">testModelAndView</a>
方法:
1 /** 2 * 返回ModelAndView设置的页面 3 * @return 4 */ 5 @RequestMapping("/testModelAndView") 6 public ModelAndView testModelAndView() { 7 8 System.out.println("testModelAndView执行了..."); 9 10 //创建ModelAndView对象 11 ModelAndView mv = new ModelAndView(); 12 13 User user = new User(); 14 user.setUsername("美美"); 15 user.setPassword("123"); 16 user.setAge(30); 17 18 //将user放入ModelAndView对象中,同时也会将user对象放入request对象中 19 mv.addObject("user", user); 20 21 //设置跳转界面 22 mv.setViewName("success"); 23 24 return mv; 25 }