![](/img/trans.png)
[英]Confusion between addAttribute and addFlashAttribute in RedirectAttributes class
[英]Spring RedirectAttributes: addAttribute() vs addFlashAttribute()
到目前為止,我的理解是關於我們的控制器請求映射方法,我們可以指定RedirectAttributes參數並在請求被重定向時使用屬性填充它。
示例:
@RequestMapping(value="/hello", method=GET)
public String hello(RedirectAttributes redirAttr)
{
// should I use redirAttr.addAttribute() or redirAttr.addFlashAttribute() here ?
// ...
return "redirect:/somewhere";
}
然后重定向屬性將在它重定向到的目標頁面上可用。
但是RedirectAttributes類有兩種方法:
已經閱讀 Spring 文檔有一段時間了,但我有點迷茫。 這兩者之間的根本區別是什么,我應該如何選擇使用哪一個?
這是區別:
addFlashAttribute()
實際上將屬性存儲在flashmap 中(它在用戶session
內部維護,並在下一個重定向請求得到滿足后刪除)
addAttribute()
本質上是根據您的屬性構造請求參數,並使用請求參數重定向到所需頁面。
所以addFlashAttribute()
的優點是你可以在你的flash 屬性中存儲幾乎任何對象(因為它根本沒有序列化到請求參數中,而是作為一個對象維護),而使用addAttribute()
因為你add 被轉換為一個普通的請求參數,你非常受限於對象類型,比如String
或原語。
假設您有 2 個控制器。如果您從一個控制器重定向到另一個控制器,則模型對象中的值在另一個控制器中將不可用。 因此,如果您想共享模型對象值,則必須在第一個控制器中說
addFlashAttribute("modelkey", "modelvalue");
然后第二個控制器的模型現在包含上面的鍵值對..
第二個問題? RedirectAttributes
類中的addAttribute
和addFlashAttribute
什么區別
addAttribute
會將值作為請求參數而不是模型傳遞,因此當您使用addAttribute
添加一些值時,您可以從request.getParameter
訪問這些值
這是代碼。我曾經用來找出發生了什么:
@RequestMapping(value = "/rm1", method = RequestMethod.POST)
public String rm1(Model model,RedirectAttributes rm) {
System.out.println("Entered rm1 method ");
rm.addFlashAttribute("modelkey", "modelvalue");
rm.addAttribute("nonflash", "nonflashvalue");
model.addAttribute("modelkey", "modelvalue");
return "redirect:/rm2.htm";
}
@RequestMapping(value = "/rm2", method = RequestMethod.GET)
public String rm2(Model model,HttpServletRequest request) {
System.out.println("Entered rm2 method ");
Map md = model.asMap();
for (Object modelKey : md.keySet()) {
Object modelValue = md.get(modelKey);
System.out.println(modelKey + " -- " + modelValue);
}
System.out.println("=== Request data ===");
java.util.Enumeration<String> reqEnum = request.getParameterNames();
while (reqEnum.hasMoreElements()) {
String s = reqEnum.nextElement();
System.out.println(s);
System.out.println("==" + request.getParameter(s));
}
return "controller2output";
}
Javadoc 描述: “FlashMap 為一個請求提供了一種存儲用於另一個請求的屬性的方法。這在從一個 URL 重定向到另一個 URL 時最常需要——例如 Post/Redirect/Get 模式。FlashMap 保存在重定向(通常在會話中)並在重定向后可用並立即刪除。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.