Spring MVC 重定向傳遞數據
1. 前言
本節課程和大家一起講解 Spring MVC 框架是如何跨請求傳遞數據的,讓數據在重定向期間能被讀出來。你需要重點掌握對 RedirectAttributes 組件的使用。
2. 查詢字符串
如果是轉發,數據模型只需要是請求作用域級別的,視圖解析器便能從數據模型中拿到所需要的數據。對于重定向,因為跨了請求,視圖無法讀出請求作用域級別的數據模型中的數據。
如果要讓數據模型中的數據被視圖識別出來,則需要提升數據模型的作用域,如升級為會話作用域級別。所謂會話作用域,意味著數據會存放在服務器的會話緩存區。如果數據使用的頻率不是很高,會產生空間上的浪費。
有沒有一種較佳的方案,即不浪費服務器空間,又能傳遞數據了?
答案是肯定的。最原始的方式便是采用查詢字符串的方式。
如下面的實例:
@RequestMapping("/response03")
public String response03(ModelMap model) throws IOException {
// 發送給客戶端的響應數據
String hello = "Hello";
model.addAttribute("data", hello);
return "redirect:/hello.jsp";
}
model 中的數據只是請求作用域級別,重定向后的 hello.jsp 中無法獲取此數據, Spring MVC 內部處理方式是把數據附加在 hello.jsp 后面。
打開瀏覽器,輸入請求 http://localhost:8888/sm-demo/response03 地址,查看瀏覽器的地址欄中的 URL 變成 http://localhost:8888/sm-demo/hello.jsp?data=Hello。
Tips:數據附加在 URL 后面是 Spring MVC 自動完成的。
把 hello.jsp 頁面中的數據讀取方式改成下面的方式(從查詢參數中讀取)。
<div style="color:red">${param.data} </div>
這種方式有 2 個缺點:
-
安全性低,數據赤裸裸地暴露在地址欄中;
-
如果數據量多,則整個 URL 變得臃腫不易維護。
多數據實例:
@RequestMapping("/response03")
public String response03(ModelMap model) throws IOException {
// 發送給客戶端的響應數據
String hello = "Hello";
model.addAttribute("data", hello);
model.addAttribute("id", 1);
return "redirect:/hello.jsp";
}
當請求后,URL 會變成 http://localhost:8888/sm-demo/hello.jsp?data=Hello&id=1 。
3. 模板方式
Spring MVC 提供有一種所謂的模板方法,和前面的以查詢字符串方法進行附加沒有多大區別。如下面的代碼,數據模型中的 data 對應數據會以 URL 變量方式傳遞。數據模型中其它數據則以查詢字符串方式進行傳遞。
@RequestMapping("/response04")
public String response04(ModelMap model) throws IOException {
// 發送給客戶端的響應數據
String hello = "Hello";
model.addAttribute("data", hello);
model.addAttribute("id", 1);
return "redirect:/test/{data}";
}
?
@RequestMapping("/test/{data}")
public String response05(@PathVariable("data") String data,@RequestParam("id") int id)
throws IOException {
System.out.println(data);
System.out.println(id);
return null;
}
當在瀏覽器中請求 http://localhost:8888/sm-demo/response04 后,瀏覽器的地址欄中會變成 :http://localhost:8888/sm-demo/test/Hello?id=1。
模板方式其本質和查詢字符串沒有太多區別。
4. 使用 Flash 屬性
Spring MVC 使用重定向時,內部會做些處理,把數據以查詢字符串或變量參數方式進行傳遞。對于簡單的數據傳遞已經足夠了。如果需要傳遞一個對象,則需要把一個對象拆分后再傳遞,顯然不是一種最佳方案。
Spring MVC 提供有 RedirectAttributes 組件,專用于重定向期間進行數據傳遞,其本質是把數據先保存在會話作用域中,但不會長時間占據會話存儲空間,當整個重定向結束后數據會自動從會話作用域中刪除。
所以,RedirectAttributes 組件中的屬性也叫 Flash 屬性。
如下面實例:用戶對象以 Flash 屬性的方式封裝在模型對象中進行傳遞。
@RequestMapping("/response05")
public String response06(RedirectAttributes model) throws IOException {
User user=new User("mk", "123");
model.addFlashAttribute("user", user);
return "redirect:/test01";
}
Tips:重定向路徑 test01 是控制器中的另一個方法,如下所示。
@RequestMapping("/test01")
public String response07(ModelMap model)
throws IOException {
User user= (User) model.get("user");
System.out.println(user);
return "hello";
}
自然,在 hello 視圖中很便捷的就能得到數據。
<body>
<div style="color:red"> ${user.userName} </div>
<div style="color:red"> ${user.userPassword} </div>
</body>
4. 小結
本章節和大家一起講解 Spring MVC 框架的重定向過程中是如何實現數據傳遞的,傳遞方式歸納起來就 2 種:
- 通過 URL 附加數據的方式傳遞數據;
- 使用 Spring MVC 提供的 RedirectAttributes 組件實現數據的傳遞。
兩種方式各有屬于自己的應用場景,數據量不多時可以使用第一種方案。數據以對象方式進行傳遞時可使用第二種方案。