Spring comes with a “ContextLoaderListener” listener to enable Spring dependency injection into session listener. In this tutorial, it revises this HttpSessionListener example by adding a Spring dependency injection a bean into the session listener.

1. Spring Beans

Create a simple counter service to print total number of sessions created.

File : CounterService.java

package com.mkyong.common;
public class CounterService{
	public void printCounter(int count){
		System.out.println("Total session created : " + count);

File : counter.xml – Bean configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	<bean id="counterService" class="com.mkyong.common.CounterService" />

2. WebApplicationContextUtils

Uses “WebApplicationContextUtils” to get the Spring’s context, and later you can get any declared Spring’s bean in a normal Spring’s way.

File : SessionCounterListener.java

package com.mkyong.common;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SessionCounterListener implements HttpSessionListener {
     private static int totalActiveSessions;
     public static int getTotalActiveSession(){
           return totalActiveSessions;
    public void sessionCreated(HttpSessionEvent arg0) {
           System.out.println("sessionCreated - add one session into counter");	
    public void sessionDestroyed(HttpSessionEvent arg0) {
           System.out.println("sessionDestroyed - deduct one session from counter");	
    private void printCounter(HttpSessionEvent sessionEvent){
          HttpSession session = sessionEvent.getSession();
          ApplicationContext ctx = 
          CounterService counterService = 
                      (CounterService) ctx.getBean("counterService");

3. Integration

The only problem is, how your web application know where to load the Spring bean configuration file? The secret is inside the “web.xml” file.

  1. Register “ContextLoaderListener” as the first listener to make your web application aware of the Spring context loader.
  2. Configure the “contextConfigLocation” and define your Spring’s bean configuration file.

File : web.xml

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
  <display-name>Archetype Created Web Application</display-name>
	<servlet-name>Spring DI Servlet Listener</servlet-name>
	<servlet-name>Spring DI Servlet Listener</servlet-name>

File : App.java

package com.mkyong.common;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class App extends HttpServlet{
  public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException{
        HttpSession session = request.getSession(); //sessionCreated() is executed
        session.setAttribute("url", "mkyong.com"); 
        session.invalidate();  //sessionDestroyed() is executed
        PrintWriter out = response.getWriter();
        out.println("<h1>Spring Dependency Injection into Servlet Listenner</h1>");

Start Tomcat, and access the URL “http://localhost:8080/SpringWebExample/Demo“.


sessionCreated - add one session into counter
Total session created : 1
sessionDestroyed - deduct one session from counter
Total session created : 0

See the console output, you get the counter service bean via Spring DI, and print the total number of sessions.


In Spring, the “ContextLoaderListener” is a generic way to integrate Spring Dependency Injection to almost all of the web application.


Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts