How do I count number of online users?

When you have a web application you might want to know how many users are currently online or connected to your website. If you have visited some web online forums you can see; usually on the first page; the list of their online users or maybe just the number of currently online users.

How do we know / count how many sessions or users are currently connected to our website. Do you care to know? Let’s see what Java Servlet API offers us on this matter.

Servlet API has an interface javax.servlet.http.HttpSessionListener, an implementation of this interface will have the ability to be notified by the servlet engine at anytime when a new session was created or destroyed.

This interface has two methods to be implemented; these methods are sessionCreated(HttpSessionEvent se) and sessionDestroyed(HttpSessionEvent se). These methods will be called as a notification that a new session was created, and the session was about to be destroyed respectively.

Now let’s create our session listener. The code below is what our class is going to be implemented.

package org.kodejava.servlet;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.ArrayList;

@WebListener
public class SessionCounter implements HttpSessionListener {
    public static final String COUNTER = "SESSION-COUNTER";
    private final List<String> sessions = new ArrayList<>();

    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("SessionCounter.sessionCreated");
        HttpSession session = event.getSession();
        sessions.add(session.getId());
        session.setAttribute(SessionCounter.COUNTER, this);
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.println("SessionCounter.sessionDestroyed");
        HttpSession session = event.getSession();
        sessions.remove(session.getId());
        session.setAttribute(SessionCounter.COUNTER, this);
    }

    public int getActiveSessionNumber() {
        return sessions.size();
    }
}

To display information of current online users we need to create a simple JSP page. This JSP file will get the number of online user from HttpSession attribute named counter that we set in our listener above.

<%@ page import="org.kodejava.servlet.SessionCounter" %>
<html>
<head>
    <title>Session Counter</title>
</head>
<body>
<%
    SessionCounter counter = (SessionCounter) session.getAttribute(
            SessionCounter.COUNTER); 
%>

Number of online user(s): <%= counter.getActiveSessionNumber() %>
</body>
</html>

The final step to make the listener working is to register it in the web.xml file. Below is the example how to register the listener in web.xml.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>Servlet Examples</display-name>
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>
</web-app>

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

18 Comments

  1. Hi, thanks for the guidance. But when I implement this code and run the project. All I get is a blank screen. Am I missing something?

    Reply
  2. I created a Java library in netbeans and saved it to a specific folder. First of all i got these errors:

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

    These three packages does not exist. Then I wrote the JSP codes in a notepad++ and saved in the same folder. I need to know what is the next step? I want to try whether the code succeed or not? What should i run to get the results?

    Reply
  3. When I run the code as well it states that there is no main can you provide more information about where exactly should i write this piece of code ???

    Reply
  4. Hi Wayan,

    I guess it will show number of active session instead of number of active users. If I am wrong can you please help me that how it is differentiating between sessions and users . Thanks in advance

    Reply
  5. Hi Wayan,

    I tried this code. But I am getting counts of sessions instead of count of users. Can you please help me how to get count of active users?

    Reply
    • Hi Abhinandan,

      You might need to create a variable that stored the username instead of the session id. When the same username is used to login you can decide whether to count this or not. Because one user might login from a different browser. If this happened is it regarded as one user or two users?

      Reply
  6. Hi Wayan. While the code works when we log into the application, the count increases by 1, when logged out/ window closed it decreases the count and again calls the sessionCreated(…) thereby increasing the count and not maintaining the accuracy. Any idea why this is happening? Thank you.

    Reply

Leave a Reply to LarkCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.