Servlet2.1之后不支持SessionContext里面getSession(String id)方法,也不存在遍歷所有會話Session的方法。但是,我們可以通過HttpSessionListener監聽器和全局靜態map自己實現一個SessionContext,然后用SessionContext管理一份服務器所有會話的Session。
1.web.xml添加一個監聽器
<listener> <listener-class>listener.MySessionListener</listener-class> </listener>
2.定義一個SessionContext:MySessionContext
public class MySessionContext {
private static HashMap mymap = new HashMap();
public static synchronized void AddSession(HttpSession session) { if (session != null) { mymap.put(session.getId(), session); } }
public static synchronized void DelSession(HttpSession session) { if (session != null) { mymap.remove(session.getId()); } }
public static synchronized HttpSession getSession(String session_id) { if (session_id == null) return null; return (HttpSession) mymap.get(session_id); } }
3.任何Session的創建和刪除都用自己的SessionContext管理起來:MySessionListener
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); } }
然后就實現了任何時候都可以通過遍歷SessionContext而得到所有會話的Session。
有什么用呢?你可以定期清理過時的Session呢!(注意,Session超時了以及你換地方登陸了並不會刪除用戶的Session,其只是Session對應的時間戳讓你無法再使用對應的Session,或者是瀏覽器的Cookie丟失了原先瀏覽器里面存在的SessionId而已,因此定時清理Session也會讓服務器內存壓力小很多)。