如何确定在任何给定时刻我的基于Servlet的应用程序正在处理哪些打开的会话 [英] How to find out what open sessions my servlet based application is handling at any given moment
问题描述
我需要编写一个servlet,当它被调用时,它获取有关当前打开的会话列表的信息.
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?
推荐答案
Implement HttpSessionListener
, give it a static Set<HttpSession>
property, add the session to it during sessionCreated()
method, remove the session from it during sessionDestroyed()
method, register the listener as <listener>
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<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中执行以下操作:
Then in your servlet just do:
Set<HttpSession> sessions = HttpSessionCollector.getSessions();
如果您想在应用程序范围内存储/获取它,以便可以使Set<HttpSession>
非静态,则让HttpSessionCollector
实现
If you rather want to store/get it in the application scope so that you can make the Set<HttpSession>
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");
}
可以在Servlet中使用,如下所示:
which you can use in Servlet as follows:
HttpSessionCollector collector = HttpSessionCollector.getCurrentInstance(getServletContext());
Set<HttpSession> sessions = collector.getSessions();
这篇关于如何确定在任何给定时刻我的基于Servlet的应用程序正在处理哪些打开的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!