//session操做類 public class SessionMap { private static Map<String,HttpSession> sesMap = new ConcurrentHashMap<String,HttpSession>(); private SessionMap(){ } private static class MapUtilsN{ private static SessionMap sessionMap = new SessionMap(); } public static SessionMap getInstance(){ return MapUtilsN.sessionMap; } public void addMap(String sessionId,HttpSession session){ if(!sesMap.containsKey(sessionId)){ sesMap.put(sessionId, session); } } public void removeMap(String sessionId){ sesMap.remove(sessionId); } public int getSize(){ return sesMap.size(); } public HttpSession getSession(String key){ return sesMap.get(key); } } //監聽session建立及銷燬 public class MySessionListner implements HttpSessionListener{ public void sessionCreated(HttpSessionEvent arg0) { SessionMap.getInstance().addMap(arg0.getSession().getId(), arg0.getSession()); } public void sessionDestroyed(HttpSessionEvent arg0) { SessionMap.getInstance().removeMap(arg0.getSession().getId()); } } //web.xml中配置監聽器 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置監聽器 --> <listener> <listener-class> practice.listner.MySessionListner </listener-class> </listener> <!-- 設置session超時時間 --> <session-config> <session-timeout>10</session-timeout> </session-config> </web-app>