How to find the number of users logged in a web application?

To find the count of number of users logged in a web application, we can use HttpSessionListener.

Create a listener class as follows

SessionCounter.java

package in.techdive.http;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounter implements HttpSessionListener
{
        private static int count;

        public SessionCounter()
        {
        }

        public void sessionCreated(HttpSessionEvent arg0)
        {
                count++;
                ServletContext sContext = arg0.getSession().getServletContext();
                synchronized (sContext)
                {
                        sContext.setAttribute("sessionCount", new Integer(count));
                }
        }

        public void sessionDestroyed(HttpSessionEvent arg0)
        {
                count--;
                ServletContext sContext = arg0.getSession().getServletContext();
                synchronized (sContext)
                {
                        sContext.setAttribute("sessionCount", new Integer(count));
                }
        }
}

Whenever a session is created, sessionCreated method will be called and when session is invalidated or destroyed, sessionDestroyed method will be called.

The above listener should be configured in the deployment descriptor as follows.

web.xml

<listener>
  <listener-class>in.techdive.http.SessionCounter</listener-class>
</listener>

The "sessionCount" attribute which has been set in the servletContext should not be modified in any other part of the application. Since we are using serveltContext in both the methods to modify the same variable, we have synchronized it for consistency.

Technology: 

Search