Thursday, September 8, 2011

How do I count number of 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's 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 is created or destroyed.

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

package org.kodejava.servlet.examples;

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

public class SessionCounter implements HttpSessionListener {
    private List sessions = new ArrayList();

    public SessionCounter() {
    }

    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        sessions.add(session.getId());

        session.setAttribute("counter", this);
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        sessions.remove(session.getId());

        session.setAttribute("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.examples.SessionCounter" %>
<html>
<head>
    <title>Session Counter</title>
</head>

<body>
<%
    SessionCounter counter = (SessionCounter) session
            .getAttribute("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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <listener>
        <listener-class>
            org.kodejava.servlet.examples.SessionCounter
        </listener-class>
    </listener>
</web-app>
 
Source : kodejava.org 

No comments:

Post a Comment