Model 消息与 Flash 消息区别

本文探讨了SpringMVC中model.addAttribute与redirectAttributes.addFlashAttribute的区别。虽然两者在实现方式上相似,但RedirectAttributes提供了addFlashAttribute方法,该方法将属性存储在session中,确保在重定向后仍可访问,而model仅将属性放入request中,不适用于重定向场景。

今天使用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 中,不适用于重定向。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值