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>();

接下來,看一下幾個重要的方法,

服務器查找Session對象的方法

客戶端每次的請求,tomcat都會在HashMap中查找對應的key為JSESSIONID的Session對象是否存在,可以查看Request的doGetSession方法源碼,如下源碼:

先看doGetSession方法中的如下代碼,這個一般是第一次訪問的情況,即創建session對象,session的創建是調用了ManagerBase的createSession方法來實現的; 另外,注意response.addSessionCookieInternal方法,該方法的功能就是上面提到的往響應頭寫入“Set-Cookie”信息;最后,還要調用session.access方法記錄下該session的最后訪問時間,因為session是可以設置過期時間的

session = manager.createSession(sessionId); // Creating a new session cookie based on that session
if ((session != null) && (getContext() != null) && getContext().getServletContext(). getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } if (session == null) { return null; } session.access(); return session;

再看doGetSession方法中的如下代碼,這個一般是第二次以后訪問的情況,通過ManagerBase的findSession方法查找session,其實就是利用map的key從ConcurrentHashMap中拿取對應的value,這里的key即requestedSessionId,也即JSESSIONID,同時還要調用session.access方法,記錄下該session的最后訪問時間;

if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) { session = null; } if (session != null) { session.access(); return (session); } }

在session對象中查找和設置key-value的方法

這個我們一般調用getAttribute/setAttribute方法:

getAttribute方法很簡單,就是根據key從map中獲取value;

setAttribute方法稍微復雜點,除了設置key-value外,如果添加了一些事件監聽(HttpSessionAttributeListener)的話,還要通知執行,如beforeSessionAttributeReplaced, afterSessionAttributeReplaced, beforeSessionAttributeAdded、 afterSessionAttributeAdded。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM