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>();
@Override
public void sessionCreated(HttpSessionEvent sessionEvent) {
sessionMap.put(sessionEvent.getSession().getId(), sessionEvent.getSession());
}

@Override
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
sessionMap.remove(sessionEvent.getSession().getId());
}
}

  • Register the Listener in web.xml
<listener>
             <listener-class>com.lalit.http.HttpSessionCounterListener</listener-class>
        </listener>
  • 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);
    %>
   <div>>
              <%= attribName %> - <%= attribValue %>
    </div>
    <%
          }
       }
   %>

No comments:

Post a Comment