How to find out what open sessions my servlet based application is handling at any given moment

后端 未结 2 1036
春和景丽
春和景丽 2020-12-20 23:14

I need to write a servlet that, when called, gets information about a list of the currently opened sessions.

Is there a way to do this?

2条回答
  •  一生所求
    2020-12-20 23:48

    Implement HttpSessionListener, give it a static Set property, add the session to it during sessionCreated() method, remove the session from it during sessionDestroyed() method, register the listener as in web.xml. Now you've a class which has all open sessions in the current JBoss instance collected. Here's a basic example:

    public HttpSessionCollector implements HttpSessionListener {
        private static final Set sessions = ConcurrentHashMap.newKeySet();
    
        public void sessionCreated(HttpSessionEvent event) {
            sessions.add(event.getSession());
        }
    
        public void sessionDestroyed(HttpSessionEvent event) {
            sessions.remove(event.getSession());
        }
    
        public static Set getSessions() {
            return sessions;
        }
    }
    

    Then in your servlet just do:

    Set sessions = HttpSessionCollector.getSessions();
    

    If you rather want to store/get it in the application scope so that you can make the Set non-static, then let the HttpSessionCollector implement ServletContextListener as well and add basically the following methods:

    public void contextCreated(ServletContextEvent event) {
        event.getServletContext().setAttribute("HttpSessionCollector.instance", this);
    }
    
    public static HttpSessionCollector getCurrentInstance(ServletContext context) {
        return (HttpSessionCollector) context.getAttribute("HttpSessionCollector.instance");
    }
    

    which you can use in Servlet as follows:

    HttpSessionCollector collector = HttpSessionCollector.getCurrentInstance(getServletContext());
    Set sessions = collector.getSessions();
    

提交回复
热议问题