《Spring實戰》讀書筆記--SpringMVC之forward與redirect

《Spring實戰》讀書筆記--SpringMVC之forward與redirect

1.forward與redirect介紹


1.1 redirect
重定向,服務器收到請求後發送一個狀態碼給客戶端,讓客戶端再從新請求,而且第一次請求中Request裏的數據消失。因此redirect至關於客戶端向服務器發出兩次請求,第一次請求的數據不會轉發給第二次請求,URL地址會變化兩次。html

1.2 forward
轉發(前往),服務器內部的重定向,在Servlet中經過RequestDispatcher轉發給另外一個程序處理請求,請求的數據依然在。因此forward至關於客戶端向服務器發送一次請求,服務器處理兩次,請求數據不會消失且URL地址只變化一次。java

2.Servlet與SpringMVC中的forward與redirect


2.1 Servlet中的forward與redirect
Servlet中的HttpServletResponse類中有sendRedirect(String location)方法直接重定向到URL爲location的地址。
應用:spring

 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.

應用:session

 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關鍵字,而後處理。
應用:mvc

 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不能傳遞數據,但咱們能夠使用其它方案傳遞數據。主要有:app

  • 經過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"。
該方法簡單有效,但傳遞數據值簡單,若數據複雜則可以使用下面的方式傳遞數據jsp

3.2 使用flash屬性
Spring提供了RedirectAttributes設置flash屬性的方法重定向傳遞參數。
原理:在重定向執行以前,全部的flash屬性會複製到session中。在重定向後,放在Session中的flash屬性會被取出,放到Model中。注:RedirectAttributes類繼承自Model類。
方式以下:ide

 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 }

4.References

http://blog.csdn.net/tenor/article/details/4077079

相關文章
相關標籤/搜索