HttpSessionListener with Spring Boot Application

Datetime:2016-08-22 23:34:32          Topic:          Share

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();"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;

            cm = ConnectionManager.getInstance();
  "Session destroyed for id " + session.getId());
        catch (Exception e)
  "SesssionListener.sessionDestroyed Unable to obtain Connection", e);
2. Register the listener from a @Configration class as shown below<br />
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;

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