Model 消息与 Flash 消息区别

今天使用SpringMVC的时候看到两个方法

model.addAttribute("message", sb.toString()) 以及

redirectAttributes.addFlashAttribute("message", sb.toString()) 

稍微深究了下发现

RedirectAttributes 继承 Model 的 addAttribute(String attributeName, Object attributeValue) 方法

但是有特殊的 addFlashAttribute(String attributeName, Object attributeValue) 方法不知道如何实现。

可以得知 RedirectAttributes 的实现类是 RedirectAttributesModelMap,其中 addFlashAttribute 的实现是调用父类对象 ModelMap 中的 addAttribute(String attributeName, Object attributeValue)

恰巧回头看 Model 中的 addAttribute(String attributeName, Object attributeValue) 方法,实现类是 ExtendedModelMap,方法 addAttribute 实质也是调用父方法 ModelMap 中 addAttribute(String attributeName, Object attributeValue)

所以两个方法的实现方式本质上是一样的,其不同的地方可以在接口 RedirectAttributes 中的注释看到:

This interface also provides a way to add flash attributes. For a general overview of flash attributes see FlashMap. You can use RedirectAttributes to store flash attributes and they will be automatically propagated to the "output" FlashMap of the current request.

使用 RedirectAttributes 会自动将当前 request 中的 attributes 放入 FlashMap 中的 “output”

其具体方法还需要进一步的探究

个人理解 addFlashAttribute 实际将消息放入 session,从而延长了生命周期,使得可以在方法跳转中仍然使用。然而 model 只将消息放入 request 中,不适用于重定向。

 


版权声明:本文为faydflowright原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。