SpringMVC重定向参数传递RedirectAttributes

SpringMVC在重定向时提供了RedirectAttributes接口来进行参数传递。

重点笔记,查官网得:

Flash attribute support is always “on” and does not need to be enabled explicitly although if not used, it never causes HTTP session creation. On each request there is an “input” FlashMap with attributes passed from a previous request (if any) and an “output” FlashMap with attributes to save for a subsequent request. Both FlashMap instances are accessible from anywhere in Spring MVC through static methods in RequestContextUtils.
Annotated controllers typically do not need to work with FlashMap directly. Instead an @RequestMapping method can accept an argument of type RedirectAttributes and use it to add flash attributes for a redirect scenario. Flash attributes added via RedirectAttributes are automatically propagated to the “output” FlashMap. Similarly, after the redirect, attributes from the “input” FlashMap are automatically added to the Model of the controller serving the target URL.

经过翻译大致的意思是(直接google翻译了,英语差+懒滴):

Spring MVC有两个主要的抽象支持flash属性。FlashMap用于FlashMapManager存储,检索和管理 FlashMap实例时用于保存Flash属性。
Flash属性支持始终处于“打开”状态,并且不需要显式启用,但如果不使用,则永远不会导致创建HTTP会话。在每个请求上都有一个“输入”,FlashMap其中包含从先前请求(如果有)传递的属性,以及一个“输出”,FlashMap其中包含要为后续请求保存的属性。这两个FlashMap 实例都可以通过静态方法从Spring MVC中的任何位置访问 RequestContextUtils。
带注释的控制器通常不需要FlashMap直接使用。相反, @RequestMapping方法可以接受类型的参数,RedirectAttributes并使用它为重定向方案添加闪存属性。添加的Flash属性 RedirectAttributes会自动传播到“输出”FlashMap。类似地,在重定向之后,来自“输入”的属性FlashMap被自动添加到 Model服务于目标URL的控制器中。

在重定向后,通过RedirectAttributes接口设置的参数直接会被设置到目标URL的Model中,也就是说在目标重定向后的页面中可以直接使用插值的方式获取(例如JSP、Freemarker等中使用${....}获取)。
从翻译中也可以看出,如果想在重定向后的controller中使用FlashMap存储的参数,那么可以直接使用RequestContextUtils此工具类调用获取,如下示例代码:

/**
* 通过该工具类获取的FlashMap对象是一个
* Map对象(该工具类需要传入HttpServletRequest对象),
* 此时可以直接通过map.get(key)方法获取到FlashAttributes设置的参数
**/
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
inputFlashMap.get("xxxxx");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值