到目前为止,我的理解是我们的控制器请求映射方法,我们可以指定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文档,但我有点迷路了。这两者之间的根本区别是什么,我应该如何选择使用哪一个呢?
发布于 2013-01-23 01:03:35
这是difference
addFlashAttribute()实际上将属性存储在闪存图中(在用户session中内部维护,下一个重定向请求完成后删除)addAttribute()本质上从属性中构造请求参数,并使用请求参数重定向到所需的页面。因此,advantage of addFlashAttribute()将使您可以在flash属性中存储几乎任何对象(因为它根本不序列化为请求params,而是作为对象维护),而对于addAttribute(),由于添加的对象被转换为正常的请求param,因此您的对象类型非常有限,比如String或原语。
发布于 2015-05-31 17:31:08
假设您有2个controllers.If,您从一个控制器重定向到另一个控制器,则模型对象中的值在另一个控制器中不可用。因此,如果您想共享模型的对象值,那么必须在第一个控制器中说明。
addFlashAttribute("modelkey", "modelvalue");然后第二个控制器的模型现在包含上面的键值对..。
第二个问题?addAttribute和addFlashAttribute在RedirectAttributes类中有什么区别?
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";
}发布于 2014-01-11 19:56:12
Javadoc description:“FlashMap为一个请求提供了一种方式来存储用于另一个请求的属性。当从一个URL重定向到另一个URL时,这是最常用的方法--例如Post/ redirecting /Get模式。FlashMap保存在重定向之前(通常在会话中),在重定向之后可以立即删除。”
https://stackoverflow.com/questions/14470111
复制相似问题