根据sessionid获取session对象

  <!-- sessionListener -->
  <listener>
   <listener-class>com.acca.comm.SessionListener</listener-class>
  </listener>
 

因为 Servlet2.1之后不支持SessionContext 里面getSession(String id) 方法。

但是,我们可以通过HttpSessionListener监听器和全局静态map自己实现一个SessionContext

 

 

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;
    }

    @SuppressWarnings("unchecked")
    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);
    }

}
 
public class SessionListener implements HttpSessionListener { 
    
    public static Map userMap = new HashMap();  
    private   MySessionContext myc=MySessionContext.getInstance();  
      
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("start...");
    myc.AddSession(httpSessionEvent.getSession());  
    }  
      
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("end...");
    HttpSession session = httpSessionEvent.getSession();  
    myc.DelSession(session);  
    }  
    } 
 
//根据sessionid获取session
MySessionContext myc= MySessionContext.getInstance();  
HttpSession sess = myc.getSession(sessionId); 

 

你可能感兴趣的:(根据sessionid获取session对象)