Spring MVC的@SessionAttribute注解小记
最近做spring mvc开发的时候要用到session,于是就想试试通过@SessionAttribute这个注解来实现保存用户登录信息的session,发现在两个control之间没法获取保存的session,纠结的GOOGLE许久后偶然在stackoverflow上发现了下面一段回答:
The @SessionAttribute annotation
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 bestored in the sessiontemporarily 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 WebRequest interface.
In other words, @SessionAttribute is for storing conversation MVC-model objects in the session (as opposed to storing them as request attributes). It's not intended for using with arbitrary session attributes. As you discovered, it only works if the session attribute is always there.
I'm not aware of any other alternative, I think you're stuck with HttpSession.getAttribute()
大概的基本意思就是: @SessionAttribute这个注解只有当你想在某个特定的事件处理中临时保存session会话(红色标注)的时候才适用,而当需要永久保存session的话,还是采用常规的方法,比如说:session.setAttribute
===========常规java操作session的方法===========