Tuesday, 16 August 2016

HttpSessionListener with Spring Boot Application

I had a requirement to implement a HttpSessionListener in my Spring Boot application which has no web.xml. To achieve this I did the following

1. My HttpSessionListener was defined as follows

 
package com.pivotal.pcf.mysqlweb.utils;

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

import org.apache.log4j.Logger;

public class SessionListener implements HttpSessionListener
{
    protected static Logger logger = Logger.getLogger("controller");
    private HttpSession session = null;

    public void sessionCreated(HttpSessionEvent event)
    {
        // no need to do anything here as connection may not have been established yet
        session  = event.getSession();
        logger.info("Session created for id " + session.getId());
    }

    public void sessionDestroyed(HttpSessionEvent event)
    {
        session  = event.getSession();
     /*
      * Need to ensure Connection is closed from ConnectionManager
      */

        ConnectionManager cm = null;

        try
        {
            cm = ConnectionManager.getInstance();
            cm.removeConnection(session.getId());
            logger.info("Session destroyed for id " + session.getId());
        }
        catch (Exception e)
        {
            logger.info("SesssionListener.sessionDestroyed Unable to obtain Connection", e);
        }
    }
}

2. Register the listener from a @Configration class as shown below
  
package com.pivotal.pcf.mysqlweb;

import com.pivotal.pcf.mysqlweb.utils.SessionListener;
import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpSessionListener;

@Configuration
public class ApplicationSessionConfiguration
{
    @Bean
    public ServletListenerRegistrationBean<HttpSessionListener> sessionListener()
    {
        return new ServletListenerRegistrationBean<HttpSessionListener>(new SessionListener());
    }
} 
Thats all you have to do to achieve this


No comments: