最近一個項目中用到了getsession根據sessionid來獲取session,但是怎麼獲取都爲空,請教N多人,才發現在servlet的api中有如下:
HttpSession
HttpSessionContext.getSession
(java.lang.String sessionId)
不贊成的用法.
Java Servlet API的版本 2.1中,還沒有將之替換掉。該方法必須返回一個空值,且將會在未來的版本中被拋棄掉。
最新的解決辦法是通過實現HttpSessionListener的sessionCreated和sessionDestroyed來實現
解決步驟:
1、在web.xml增加監聽:
<listener>
<listener-class>com.aceway.util.LoginSessionListener</listener-class>
</listener>
2、LoginSessionListener:
LoginSessionListener方法實現了HttpSessionListener,並且重寫sessionCreated和sessionDestroyed方法
public static Map userMap = new HashMap(); //創建了一個對象來保存session的
private MySessionContext myc=MySessionContext.getInstance(); //MySessionContext是實現session的讀取和刪除增加 單例模式
public void sessionCreated(HttpSessionEvent event)
{
myc.AddSession(event.getSession());
}
public void sessionDestroyed(HttpSessionEvent event)
{
HttpSession session = event.getSession();
myc.DelSession(session);
}
3、session的單例管理
- package com.aceway.flex;
- import java.util.*;
- import javax.servlet.http.HttpSession;
- public class MySessionContext
- {
- private static MySessionContext instance;
- private HashMap mymap;
- private MySessionContext()
- {
- mymap = new HashMap();
- }
- public static MySessionContext getInstance()
- {
- if (instance== null )
- {
- instance = new MySessionContext();
- }
- return instance;
- }
- public synchronized void AddSession(HttpSession session)
- {
- if (session!= null )
- {
- mymap.put(session.getId(), session);
- }
- }
- public synchronized void DelSession(HttpSession session)
- {
- if (session!= null )
- {
- mymap.remove(session.getId());
- }
- }
- public synchronized HttpSession getSession(String session_id)
- {
- if (session_id== null ) return null ;
- return (HttpSession)mymap.get(session_id);
- }
- }
4、這樣我們就可以單例來獲取session
private MySessionContext myc=MySessionContext.getInstance();
HttpSession session = myc.getSession(SessionId);