會員註冊 / 登入  |  電腦版  |  Jump to bottom of page

網頁程式設計 Web Development » 如何由 session Id 取得Java HttpSession 物件

發表人: andowson, 七段學員
2009-12-11 19:43:00
今天遇到了一個問題,就是如果想要在網站關閉時將正在連線的session手動斷線後再關閉資料庫連線,需要取得session物件,但之前對連線資料只有紀錄到sessionId而已。要由sessionId字串去建構出一個HttpSession物件對Java而言似乎不是合法的方法。
搜尋了一下,找到一篇文章,建議的作法是可以將session物件紀錄到ServletContext物件(其實就是一個Map物件)去,用sessionId當作key, session物件當作value,則要取回session時用ServletContext.getAttribute(sessionId)即可。而session進入和離開ServletContext的時間點可以用一個HttpSessionListener來管理,改寫sessionCreated、sessionDestroyed這兩個methods即可:

加入及移除session

@Override
public void sessionCreated(final HttpSessionEvent se) {
final HttpSession session = se.getSession();
final ServletContext context = session.getServletContext();
context.setAttribute(session.getId(), session);
}

@Override
public void sessionDestroyed(final HttpSessionEvent se) {
final HttpSession session = se.getSession();
final ServletContext context = session.getServletContext();
context.removeAttribute(session.getId());
}


取回session物件

private HttpSession getSession(final String sessionId) {
final ServletContext context = getServletContext();
final HttpSession session = (HttpSession) context.getAttribute(sessionId);
return session;
}


參考資料:
http://stackoverflow.com/questions/1499581/how-can-i-manually-load-a-java-session-using-a-jsessionid




會員註冊 / 登入  |  電腦版  |  Jump to top of page