Wednesday, April 1, 2015

Displaying list of sessions and their attributes

If you are working on a web application and want to display the list of all sessions and their attributes than follow along. Java servlet API does not gives a convenient method to get the list of all sessions. In Tomcat, if you just want to see the list of sessions than you can install the manager application that comes with tomcat and access it using http://<tomcat server ip>/manager. Other servers provide their own way of accessing the data.

If you want to access the session details in your program in a server neutral way, may be to build some utility than the following steps can be used to build such a system.

  • Write a HttpSessionListener which maintains a collection of Map. I am using Map here but it can be any collection type based on your end

public class HttpSessionCounterListener implements HttpSessionListener {

public static Map<String,HttpSession> sessionMap = new HashMap<String,HttpSession>();
public void sessionCreated(HttpSessionEvent sessionEvent) {
sessionMap.put(sessionEvent.getSession().getId(), sessionEvent.getSession());

public void sessionDestroyed(HttpSessionEvent sessionEvent) {

  • Register the Listener in web.xml
  • A sample JSP page to display the session and their attributes. Import the required class in the jsp page
<%@ page language="java" import="java.util.*,com.lalit.http.*" %>
for (Map.Entry<String, HttpSession> entry : HttpSessionCounterListener.sessionMap.entrySet()){
           for (Enumeration e = entry.getValue().getAttributeNames(); e.hasMoreElements(); ) {     
                    String attribName = (String) e.nextElement();
                   Object attribValue = entry.getValue().getAttribute(attribName);
              <%= attribName %> - <%= attribValue %>

No comments:

Post a Comment