您的位置:首页 > 编程语言 > Java开发

spring mvc @SessionAttributes的坑爹之处

2013-08-05 17:21 375 查看
来自springmvc3.2.1官方语句
NOTE: Session attributes as indicated using this annotation
* correspond to a specific handler's model attributes, getting transparently

* stored in a conversational session. Those attributes will be removed once

* the handler indicates completion of its conversational session. Therefore,

* use this facility for such conversational attributes which are supposed

* to be stored in the session temporarily during the course of a

* specific handler's conversation.

*
* For permanent session attributes, e.g. a user authentication object,

* use the traditional
session.setAttribute
method instead.

* Alternatively, consider using the attribute management capabilities of the

* generic {@link org.springframework.web.context.request.WebRequest} interface.
某种程度上,它意图让你用在一种存活时间比session短,比request长的会话中。而对于像用户身份信息等,还是应该使用session.setAttribute .
这段话写的很模糊,那么,实际上,哪些对象将会被加入session,然后如何获取到,然后何时销毁呢?
我们一个一个来追查。
1. 哪些对象何时加入session
跟踪一下, spring 在处理完modelAndView 之后,会调用HandlerMethodInvoker.updateModelAttributes,其会遍历model中的key,如果 key在 SessionAttributes中,则加入

sessionAttributeStore。

2. 如何获取 session中的对象

在spring 处理modelAndView之前,先检查是否有SessionAttributes 注释,有则获取了 sessionAttributeStore中 对应的属性,然后加入了 model中。

因此如果是在AController里使用 @sessionAttributes("xx"), 并成功设置了该属性 , 而在BController 里没有使用 @sessionAttributes("xx"), 那么BController 的方法参数里,使用 @ModelAttribute("xx") String xx, 是取不到sessionAttributeStore
中的值的。如果你想在其它的Controller获取session的值就要在Bcontroller前面加@sessionAttributes("xx"),因为要初始化 xx后才能在方法参数中通过@ModelAttribute("xx")去获取session里面的值


3. 何时销毁

需要手动调用 sessionStatus.setComplete, 才会销毁 @SessionAttributes 中对应的session属性 。这里需要留意,要记得销毁用不着的session对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: