最近做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的方法===========

Java Servlet定义了一个HttpSession接口,实现的Session的功能,在Servlet中使用Session的过程如下:

(1) 使用HttpServletRequest的getSession方法得到当前存在的session,如果当前没有定义session,则创建一个新的session,还可以使用方法getSession(true)

(2) 写session变量。可以使用方法HttpSession.setAttribute(name,value)来向Session中存储一个信息。也可以使用HttpSession.putValue(name,value),但这个方法已经过时了。

(3)读Session变量。可以使用方法HttpSession.getAttribute(name)来读取Session中的一个变量值,如果name是一个没有定义的变量,那么返回的是null。需要注意的是,从getAttribute读出的变量类型是Object,必须使用强制类型转换,比如:

String uid = (String) session.getAttribute("uid");

也可以使用HttpSession.getValue(name),但是这个方法也已经过时了。

(4) 关闭session,当时用完session后,可以使用session.invalidate()方法关闭session。但是这并不是严格要求的。因为,Servlet引擎在一段时间之后,自动关闭seesion。