Creating a servlet to get the active number of sessions in Tomcat over the web

Last two blog posts I explored how to get the number of active sessions either directly through Tomcat (, or through the application (particularly in Vaadin,

This blog post will explore putting both together and getting the session data through a servlet mapped to a URL. This way an admin can get the stats for a particular server right through a browser.

Let’s start with defining a servlet in web.xml:


Now you have a servlet called SessionStats defined to the /SessionStats on your Tomcat server, which will map to the class.

In the SessionStats we’ll query the Tomcat level sessions, and the sessions the application is tracking, and return them as easy to read HTML:

public class SessionStats extends HttpServlet {
 private String message;

 public void init(final ServletConfig config) throws ServletException {}

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  PrintWriter out = response.getWriter();

 private void getSessionStats() throws Exception {
  message = "";

  final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
  ObjectName objectName = new ObjectName("Catalina:type=Manager,context=/,host=localhost");

  int activeSessions = (Integer) mBeanServer.getAttribute(objectName, "activeSessions");

  message += "Active Sessions Reported By Tomcat: " + activeSessions + ".
  message += "
  message += "Active/Idle User Sessions Reported By Application: " + ApplicationLevelTracker.browserTabUniqueIDToIdleTimeHashMap.size() + ".
  message += "

  Set keySet = ApplicationLevelTracker.browserTabUniqueIDToIdleTimeHashMap.keySet();
  for (String key: keySet) {
   Pair < Boolean, Long > pair = ApplicationLevelTracker.browserTabUniqueIDToIdleTimeHashMap.get(key);
   String userId = key.split(":")[0];
   String activeOrIdle = (pair.getElement0() ? "idle" : "active");
   Date timeStamp = new Date(pair.getElement1());
   message += "User ID " + userId + " is logged in with a tab open that was last reported as " + activeOrIdle + " at " + timeStamp + "
  message += "

So as you can see, the Tomcat session stats are queried, and displayed. And then the ApplicationLevelTracker is used to loop through a HashMap of users logged in and their idle/active as-of timestamp is displayed. This information can be useful to a system administrator in many ways, such as when determining if a server is in use and should not be taken offline. And it can be accessed through a browser by visiting: http://hostname/SessionStats