Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

Then in your servlet just do:

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

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");
}

which you can use in Servlet as follows:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...