Well, the best solution I found is to set the HttpSessionListener :) for this we need to override some methods:
public class HttpSessionCollector implements HttpSessionListener { private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>(); @Override public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); sessions.put(session.getId(), session); } @Override public void sessionDestroyed(HttpSessionEvent event) { sessions.remove(event.getSession().getId()); } public static HttpSession find(String sessionId) { return sessions.get(sessionId); } public static Map<String, HttpSession> getSessions() { return sessions; }
}
and then set the listener to / WEB -INF / web.xml
<web-app> <listener> <listener-class>[yourpack].HttpSessionCollector</listener-class> </listener> ... </web-app>
Now we can call anywhere in the HttpSessionCollector package. for example, to get all valid sessions, we only have:
private Map<String, HttpSession> sessions; sessions=HttpSessionCollector.getSessions();
source share