一、Tomcat中的session实现
Tomcat中一个会话对应一个session,其实现类是StandardSession,查看源码,可以找到一个attributes成员属性,即存储session的数据结构,为ConcurrentHashMap,支持高并发的HashMap实现;
/**
* The collection of user data attributes associated with this Session.
*/
protected Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
那么,tomcat中多个会话对应的session是由谁来维护的呢?ManagerBase类,查看其代码,可以发现其有一个sessions成员属性,存储着各个会话的session信息:
/**
* The set of currently active Sessions for this Manager, keyed by
* session identifier.
*/
protected Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();
二、Map集合中保存的对象是对象的引用地址
session中存入对象后,修改对象的属性值后没有再次存入session,session中存放的对象也会发生改变
原因分析:
session底层其实是用ConcurrentHashMap保存数据的,下面就以Map集合进行分析
@Test
public void test35() throws Exception{
User user = new User();
user.setName("王二狗").setAge(18);
Map<String,User> map = new HashMap<>();
map.put("user",user);
System.out.println(map.get("user"));
user.setName("王三狗").setAge(20);
System.out.println(map.get("user"));
}
发现前后打印的信息发生了改变
由此可见,在Map集合中保存的对象并不是对象本身,而是对象的引用地址。当对象放入Map集合后修改对象的属性值,然后再次从Map中取值,实际上是根据的引用地址去找此对象。同理,session中保存的数据也是一样。