web.xml中context-param后加入
<!-- Spring 容器加载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.xxx.app.MySessionListener</listener-class>
</listener>
MySessionListener类
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
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);
}
}
MySessionContext类
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;
public class MySessionContext {
private static ConcurrentHashMap<String, HttpSession> mymap = new ConcurrentHashMap<String, HttpSession>();
public static Log logger = LogFactory.getLog(MySessionContext.class);
public static void addSession(HttpSession session) {
if (session != null) {
logger.debug("add session:"+session.getId());
mymap.put(session.getId(), session);
}
}
public static void delSession(HttpSession session) {
if (session != null) {
logger.debug("remove session:"+session.getId());
mymap.remove(session.getId());
}
}
public static HttpSession getSession(String session_id) {
if (session_id == null)
return null;
return (HttpSession) mymap.get(session_id);
}
}