Java中如何通过SessionId获取Session

1、MySessionContext.java

public class MySessionContext {

    private static HashMap<String,Object> sessionIdMap = new HashMap<String,Object>();

    public static synchronized void addSession(HttpSession session) {
        if (session != null) {
        sessionIdMap.put(session.getId(), session);
        }
    }

    public static synchronized void delSession(HttpSession session) {
        if (session != null) {
        sessionIdMap.remove(session.getId());
        }
    }

    public static synchronized HttpSession getSession(String session_id) {
        if (sessionIdMap.containsKey(session_id)){
        return (HttpSession) sessionIdMap.get(session_id);
        }else{
        return null;
        }
    }
}

2、MySessionListener.java

public class MySessionListener implements HttpSessionListener{

public void sessionCreated(HttpSessionEvent httpSessionEvent) {
MySessionContext.addSession(httpSessionEvent.getSession());
}

public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
MySessionContext.delSession(session);
}

}

3、web.xml

<!-- 自定义监听器:session监听 -->
  <listener>
  <listener-class>MySessionListener</listener-class>

  </listener>

4、根据sessionId获得session对象

HttpSession hs = MySessionContext.getSession(sessionId);

猜你喜欢

转载自blog.csdn.net/cnjsyzgl/article/details/80339833
今日推荐