《Spring实战》读书笔记--SpringMVC之forward与redirect
1.forward与redirect介绍
1.1 redirect
重定向,服务器收到请求后发送一个状态码给客户端,让客户端再重新请求,并且第一次请求中Request里的数据消失。所以redirect相当于客户端向服务器发出两次请求,第一次请求的数据不会转发给第二次请求,URL地址会变化两次。
1.2 forward
转发(前往),服务器内部的重定向,在Servlet中通过RequestDispatcher转发给另一个程序处理请求,请求的数据依然在。所以forward相当于客户端向服务器发送一次请求,服务器处理两次,请求数据不会消失且URL地址只变化一次。
2.Servlet与SpringMVC中的forward与redirect
2.1 Servlet中的forward与redirect
Servlet中的HttpServletResponse类中有sendRedirect(String location)方法直接重定向到URL为location的地址。
应用:
1 @WebServlet(name="deleteOneServlet",urlPatterns="/deleteOne.action") 2 public class DeleteOneServlet extends HttpServlet{ 3 private static final long serialVersionUID = 1L; 4 private ContentService contentService = new ContentService(); 5 @Override 6 protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { 7 // 从页面中获取数据 8 String id = req.getParameter("id"); 9 // 调用Servive执行业务逻辑 10 contentService.deleteOne(id); 11 // 重定向 12 resp.sendRedirect("/list.action"); 13 } 14 }
Servlet可以通过HttpServletRequest类的getRequestDispatcher(String path)获得RequestDispatcher对象,该通过该对象的forward(ServletRequest request, ServletResponse response)方法转发请求与相应给任何资源(如Servlet、HTML file、JSP file)。
RequestDispatcher类的API
1 package javax.servlet; 2 public interface RequestDispatcher{ 3 public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException; 4 public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException; 5 } 6 API上的介绍: 7 Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. 8 The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. 9 10 This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.
应用:
1 @WebServlet(name="query",urlPatterns="/query.action") 2 public class QueryServlet extends HttpServlet{ 3 private static final long serialVersionUID = 1L; 4 private ContentService contentService = new ContentService(); 5 @Override 6 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 7 // 从页面获取参数 8 String command = req.getParameter("command"); 9 String description = req.getParameter("description"); 10 // 调用Service处理业务逻辑 11 List<Message> messages = contentService.query(command, description); 12 // 向页面传递值 13 req.setAttribute("messages", messages); 14 req.setAttribute("command", command); 15 req.setAttribute("description", description); 16 // 转发到视图中 17 req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, resp); 18 } 19 }
2.2 SpringMVC中的Servlet
SpringMVC是基于Servlet的Web MVC框架,所以forward与redirect的处理结果一样,方式更为简单。SpringMVC中的InternalResourceViewResolver视图解析器会识别redirect与forward关键字,然后处理。
应用:
1 @Controller 2 @RequestMapping(value="/springMVC") 3 public class UserController { 4 @RequestMapping(value="/login") 5 public String login() { 6 return "login"; 7 } 8 9 @RequestMapping(value="/upload", method=RequestMethod.POST) 10 public String fileUpload(@RequestPart(value="file") MultipartFile multipartFile) throws Exception{ 11 String path = "E:/java/fileupload/" + multipartFile.getOriginalFilename(); 12 multipartFile.transferTo(new File(path)); 13 // 重定向 14 return "redirect:/springMVC/index"; 15 // 转发 16 return "foward:/springMVC/index"; 17 } 18 }
3. SpringMVC重定向传递数据
从上面我们可以看出redirect不能传递数据,但我们可以使用其它方案传递数据。主要有:
- 通过URL模板以路径变量或查询参数形式传递数据
- 通过flash属性传递数据
3.1 通过URL模板进行重定向
方式如下:
1 @Controller 2 @RequestMapping(value="/springMVC") 3 public class UserController { 4 @RequestMapping(value="/index/{name}",method=RequestMethod.GET) 5 public String index(@PathVariable(value="name") String name, 6 @RequestParam(value="id") int id) { 7 System.out.println(name + id); 8 return "login"; 9 } 10 11 @RequestMapping(value="/data/{id}",method=RequestMethod.GET) 12 public String data(@PathVariable(value="id") int id, Model model) { 13 model.addAttribute("id", id); 14 model.addAttribute("name", "Tom"); 15 return "redirect:/springMVC/index/{name}"; 16 } 17 }
使用模板方式时,若使用了占位符则变为路径参数,否则变为请求变量。所以以上重定向URL路径变为"/springMVC/index/Tom?id=5"。
该方法简单有效,但传递数据值简单,若数据复杂则可使用下面的方式传递数据
3.2 使用flash属性
Spring提供了RedirectAttributes设置flash属性的方法重定向传递参数。
原理:在重定向执行之前,所有的flash属性会复制到session中。在重定向后,放在Session中的flash属性会被取出,放到Model中。注:RedirectAttributes类继承自Model类。
方式如下:
1 @Controller 2 @RequestMapping(value="/springMVC") 3 public class UserController { 4 @RequestMapping(value="/index",method=RequestMethod.GET) 5 public String index(User user) { 6 System.out.println(user); 7 return "login"; 8 } 9 10 @RequestMapping(value="/data/{id}",method=RequestMethod.GET) 11 public String data(@PathVariable(value="id") int id, RedirectAttributes model) { 12 User user = new User(id,"Tom"); 13 model.addFlashAttribute("user", user); 14 return "redirect:/springMVC/index"; 15 } 16 }