5

我需要编写一个 servlet,当它被调用时,它会获取有关当前打开的会话列表的信息。

有没有办法做到这一点?

4

2 回答 2

7

实现HttpSessionListener,给它一个static Set<HttpSession>属性,在方法期间将会话添加到它,在sessionCreated()方法期间从中删除会话sessionDestroyed(),将侦听器注册为<listener>in web.xml。现在你有一个类,它收集了当前 JBoss 实例中的所有打开会话。这是一个基本示例:

public HttpSessionCollector implements HttpSessionListener {
    private static final Set<HttpSession> sessions = ConcurrentHashMap.newKeySet();

    public void sessionCreated(HttpSessionEvent event) {
        sessions.add(event.getSession());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        sessions.remove(event.getSession());
    }

    public static Set<HttpSession> getSessions() {
        return sessions;
    }
}

然后在您的 servlet 中执行以下操作:

Set<HttpSession> sessions = HttpSessionCollector.getSessions();

如果您想在应用程序范围内存储/获取它以便您可以制作Set<HttpSession> 非静态的,那么也让HttpSessionCollector实现添加以下方法:ServletContextListener

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<HttpSession> sessions = collector.getSessions();
于 2010-01-22T00:43:59.520 回答
3

Perhaps using a JMX bean is more elegant and needs no code. Just read the value of

data: jboss.web:type=Manager,path=/myapplication,host=localhost" activeSessions

于 2010-01-26T02:41:42.657 回答