spring mvc @SessionAttributes的坑爹之处

来自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对象。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值