<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Latest posts for the topic "如何由 session Id 取得Java HttpSession 物件"]]></title>
		<link>https://forum.andowson.com/posts/list/5.page</link>
		<description><![CDATA[Latest messages posted in the topic "如何由 session Id 取得Java HttpSession 物件"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>如何由 session Id 取得Java HttpSession 物件</title>
				<description><![CDATA[ 今天遇到了一個問題，就是如果想要在網站關閉時將正在連線的session手動斷線後再關閉資料庫連線，需要取得session物件，但之前對連線資料只有紀錄到sessionId而已。要由sessionId字串去建構出一個HttpSession物件對Java而言似乎不是合法的方法。
<br>
搜尋了一下，找到一篇文章，建議的作法是可以將session物件紀錄到ServletContext物件（其實就是一個Map物件）去，用sessionId當作key, session物件當作value，則要取回session時用ServletContext.getAttribute(sessionId)即可。而session進入和離開ServletContext的時間點可以用一個HttpSessionListener來管理，改寫sessionCreated、sessionDestroyed這兩個methods即可：
<br>
<br>
加入及移除session
<br>
[code]
<br>
 @Override 
<br>
 public void sessionCreated(final HttpSessionEvent se) { 
<br>
 final HttpSession session = se.getSession(); 
<br>
 final ServletContext context = session.getServletContext(); 
<br>
 context.setAttribute(session.getId(), session); 
<br>
 } 
<br>
<br>
 @Override 
<br>
 public void sessionDestroyed(final HttpSessionEvent se) { 
<br>
 final HttpSession session = se.getSession(); 
<br>
 final ServletContext context = session.getServletContext(); 
<br>
 context.removeAttribute(session.getId()); 
<br>
 } 
<br>
[/code]
<br>
<br>
取回session物件
<br>
[code]
<br>
 private HttpSession getSession(final String sessionId) { 
<br>
 final ServletContext context = getServletContext(); 
<br>
 final HttpSession session = (HttpSession) context.getAttribute(sessionId); 
<br>
 return session; 
<br>
 } 
<br>
[/code]
<br>
<br>
參考資料：
<br>
http://stackoverflow.com/questions/1499581/how-can-i-manually-load-a-java-session-using-a-jsessionid]]></description>
				<guid isPermaLink="true">https://forum.andowson.com/posts/preList/371/713.page</guid>
				<link>https://forum.andowson.com/posts/preList/371/713.page</link>
				<pubDate><![CDATA[Fri, 11 Dec 2009 19:43:00]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
	</channel>
</rss>