Search code examples
tomcatservletsjava-ee-6tomcat7

How can I use catlina api of tomcat to access session administration


How can I use catlina api of tomcat to access session administration. I have a requirement to invalidate session of other users from my code.


Solution

  • I personally prefer not to bind to Tomcat packages and get away with javax.servlet API as much as I can, for obvious reasons. Your task can be achieved by creating a session listener and keeping all sessions in a WeakHashMap, like so

    <!-- your webapp's web.xml -->
    <listener>
      <listener-class>path.to.SessionListener</listener-class>
    </listener>
    
    class SessionListener implements HttpSessionListener {
       private static final Map<String, HttpSession> sessions = Collections.synchronizedMap(new WeakHashMap<String, HttpSession>());
    
       public void sessionCreated(HttpSessionEvent event) {
          sessions.put(event.getSession().getId(), event.getSession());
       }
    
       public void sessionDestroyed(HttpSessionEvent event) {
          sessions.remove(event.getSession().getId());
       }
    }
    

    The rest is as easy as adding another method to iterate through all sessions and invalidate them.