Tracking Session using HttpSessionListener

0

You want to know how many concurrent users are there at any point of time. We will keep an application level SessionTracker object which will increment the sessions count moment a session starts and decrement when it is destroyed.
In this article, we will see an example of how to track the active sessions when a session is created or destroyed.

Bean to track Session

Let’ts create a simple bean which will hold the session count. It has methods incrementSessionCount() and decrementSessionCount() to help track the sessions. We also would like to have a method to return us the session count as at some point we would like an MBean to add session count as one of its attributes.

SessionTracker:

package com.javarticles.servlet;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Logger;

public class SessionTracker {
    private AtomicLong sessionCount = new AtomicLong(0);

    void incrementSessionCount() {
        LOGGER.warn("Increment the session count");
        sessionCount.incrementAndGet();
    }

    public long getSessionCount() {
        LOGGER.warn("Current session count " + sessionCount.get());
        return sessionCount.get();
    }

    void decrementSessionCount() {
        sessionCount.decrementAndGet();
    }

    private static final Logger LOGGER = Logger.getLogger(SessionTracker.class);
}

We will use spring to manage the bean so let’s add it to our applicationContext.xml.

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
	default-lazy-init="true">
	<bean id="sessionTracker" class="com.javarticles.servlet.SessionTracker"
		scope="singleton"></bean>
</beans>

We will implement a new HttpSessionListener listener for tracking sessions. This will be called every time a session is created or destroyed. We will have to specify this listener in web.xml.

In sessionCreated, we will first get the SessionTracker bean from spring’s application context and then call code>sessionTracker.incrementSessionCount().
In sessionCreated, we will call code>sessionTracker.decrementSessionCount() to decrement the session count.

SessionTrackerHttpSessionListener:

package com.javarticles.servlet;

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

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SessionTrackerHttpSessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        LOGGER.warn("In SessionTrackerHttpSessionListener. In SessionCreated");
        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(event.getSession()
                        .getServletContext());
        SessionTracker sessionTracker = (SessionTracker) context
                .getBean("sessionTracker");
        sessionTracker.incrementSessionCount();
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(event.getSession()
                        .getServletContext());
        SessionTracker sessionTracker = (SessionTracker) context
                .getBean("sessionTracker");
        sessionTracker.decrementSessionCount();
    }

    private static final Logger LOGGER = Logger
            .getLogger(SessionTrackerHttpSessionListener.class);
}

We will get the above bean in index.jsp and print the session count.

index.jsp:

<%@page import="com.javarticles.servlet.SessionTracker"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page
	import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<html>
<body>
	<%
	    ApplicationContext context = (ApplicationContext) WebApplicationContextUtils
	            .getWebApplicationContext(application);
	    SessionTracker sessionTracker = (SessionTracker) context
	            .getBean("sessionTracker");
	%>
	<h2>
		Hello World! You are
		<%=sessionTracker.getSessionCount()%>
		visitor
	</h2>
</body>
</html>

Let’s add above listener to <listener> element.

web.xml:

<!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>
	<display-name>Archetype Created Web Application</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath*:/applicationContext.xml,
		</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>	
	<listener>
		<listener-class>com.javarticles.servlet.SessionTrackerHttpSessionListener</listener-class>
	</listener>
</web-app>

We will use log4j for logging messages. Below is the configuration. In case you want to know more about log4j, see Log4j Example.

log4j.properties

# Root logger option
log4j.rootLogger=WARN, file, stdout
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/javarticle.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Run the example

Every time you open a browser and open http://localhost:8080/MBeanExample/, you will get a new session and an increment in the session count.

Session Count

Session Count

Output:

Apr 25, 2015 8:06:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1082 ms
2015-04-25 20:06:39 WARN  SessionTrackerHttpSessionListener:15 - In SessionTrackerHttpSessionListener. In SessionCreated
2015-04-25 20:06:39 WARN  SessionTracker:11 - Increment the session count
2015-04-25 20:06:39 WARN  SessionTracker:16 - Current session count 1
2015-04-25 20:07:05 WARN  SessionTrackerHttpSessionListener:15 - In SessionTrackerHttpSessionListener. In SessionCreated
2015-04-25 20:07:05 WARN  SessionTracker:11 - Increment the session count
2015-04-25 20:07:05 WARN  SessionTracker:16 - Current session count 2

Download the source code

This was an example about tracking session. You can download the source code here: SessionTrackingExample.zip

Share.

Comments are closed.