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