Spring Boot + Session Listener
In this Spring Boot article, we will look at the Spring Boot session listener, also known as the Spring Boot HttpSessionListener. This tutorial will cover the basics of creating and registering a HttpSessionListener with our spring boot application.
What is HttpSessionListener?
When an HTTP session is created or deleted, the HttpSessionListener receives a notification. To make use of it, we must implement the sessionCreated() and sessionDestroyed() methods. The sessionCreated() method is called when a new session is established/created, whereas sessionDestroyed() is called when the session expires or when it is invalidated via the invalidate() method. In order to create a Http Session Listener in Spring Boot, we must first create a HttpSessionListener bean.
When a session is created or deleted, HttpSessionListener is used to perform various important tasks.
Let's start developing Spring Boot + Session Listener Example.
Create Spring Boot Project
Create Spring Boot Project from Spring Initializer https://start.spring.io/.
Maven Dependency
Add spring-boot-starter-web dependency to test the application using rest controller.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-session-listener</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-session-listener</name>
<description>Spring Boot Session Listener Example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Take a look at our suggested posts:
Create HttpSessionListener
Create a Custom HttpSessionListener bean with a session counter that will be updated when new sessions are created and to update our counter when a session is destroyed or invalidated.
The @WebListener annotation is being used to annotate a listener to receive events for various web application context actions.
In this class, we are using @WebListener annotation to register a class as a listener for the HttpSessionListener's events.
package com.techgeeknext.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;
@WebListener
public class HttpSessionListenerConfig implements HttpSessionListener {
private static final Logger LOG= LoggerFactory.getLogger(HttpSessionListenerConfig.class);
private final AtomicInteger activeSessions;
public HttpSessionListenerConfig() {
super();
activeSessions = new AtomicInteger();
}
/**
* This method will be called when session created
* @param sessionEvent
*/
@Override
public void sessionCreated(HttpSessionEvent sessionEvent) {
LOG.info("-------Incrementing Session Counter--------");
activeSessions.incrementAndGet();
LOG.info("-------Session Created--------");
sessionEvent.getSession().setAttribute("activeSessions",activeSessions.get());
LOG.info("Total Active Session : {} ", activeSessions.get());
}
/**
* This method will be automatically called when session destroyed
* @param sessionEvent
*/
@Override
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
LOG.info("-------Decrementing Session Counter--------");
activeSessions.decrementAndGet();
sessionEvent.getSession().setAttribute("activeSessions",activeSessions.get());
LOG.info("-------Session Destroyed--------");
}
}
You can also use Bean, instead of WebListener, replace above code with below code:
// bean for http session listener
@Bean
public HttpSessionListener httpSessionListener() {
return new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session Created with session id+" + se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session Destroyed, Session id:" + se.getSession().getId());
}
};
}
SpringBootApplication
If you are using @WebListener, remember to add add @ServletComponentScan with @SpringBootApplication annotation.
package com.techgeeknext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class SpringBootSessionListenerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSessionListenerApplication.class, args);
}
}
Rest Controller
Create Rest Controller Endpoints to test the events by creating session and destroying session.
package com.techgeeknext.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@RestController
public class SessionListenerController {
private static final Logger LOG = LoggerFactory.getLogger(SessionListenerController.class);
@GetMapping("/create-new-session")
public String createNewSession(HttpServletRequest request, HttpServletResponse response) {
HttpSession sessionObj = request.getSession(false);
//check session exist or not
//if not available create new session
if (sessionObj == null) {
LOG.info("Session not available, creating new session.");
sessionObj = request.getSession(true);
}
String activeSessions = sessionObj.getAttribute("activeSessions")!=null
?sessionObj.getAttribute("activeSessions").toString()
:"0";
return "Session is available now with total active sessions : "+activeSessions;
}
@GetMapping("/destroy-active-session")
public String removeSession(HttpServletRequest request, HttpServletResponse response) {
HttpSession sessionObj = request.getSession(false);
if (sessionObj != null) {
sessionObj.invalidate();
return "Session destroyed, now there are no active sessions.";
}
return "Session not available to destroy.";
}
}
Test HttpSessionListener
Run the Spring Boot application and test below use cases to validate the events:
- Create Session: Use this url http://localhost:8080/create-new-session to see session created and observe the logs printed from the listener method.
- Create more new session: Create new session by using http://localhost:8080/create-new-session in new browser..
- Destroy Session: Use the url http://localhost:8080/destroy-active-session to see session is destroyed and logs printed from the listener method.
- Console logs:
12:55:47.971 INFO 25840 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 12:55:47.982 INFO 25840 --- [main] c.t.SpringBootSessionListenerApplication : Started SpringBootSessionListenerApplication in 3.599 seconds (JVM running for 13.556) 12:55:53.078 INFO 25840 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 12:55:53.079 INFO 25840 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 12:55:53.096 INFO 25840 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 16 ms 12:55:53.185 INFO 25840 --- [nio-8080-exec-1] c.t.c.SessionListenerController : Session not available, creating new session. 12:55:53.194 INFO 25840 --- [nio-8080-exec-1] c.t.listener.HttpSessionListenerConfig : -------Incrementing Session Counter-------- 12:55:53.195 INFO 25840 --- [nio-8080-exec-1] c.t.listener.HttpSessionListenerConfig : -------Session Created-------- 12:55:53.196 INFO 25840 --- [nio-8080-exec-1] c.t.listener.HttpSessionListenerConfig : Total Active Session : 1 12:55:57.972 INFO 25840 --- [nio-8080-exec-2] c.t.c.SessionListenerController : Session not available, creating new session. 12:55:57.974 INFO 25840 --- [nio-8080-exec-2] c.t.listener.HttpSessionListenerConfig : -------Incrementing Session Counter-------- 12:55:57.975 INFO 25840 --- [nio-8080-exec-2] c.t.listener.HttpSessionListenerConfig : -------Session Created-------- 12:55:57.975 INFO 25840 --- [nio-8080-exec-2] c.t.listener.HttpSessionListenerConfig : Total Active Session : 2 12:56:03.707 INFO 25840 --- [nio-8080-exec-7] c.t.listener.HttpSessionListenerConfig : -------Decrementing Session Counter-------- 12:56:03.708 INFO 25840 --- [nio-8080-exec-7] c.t.listener.HttpSessionListenerConfig : -------Session Destroyed--------
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot + Session Listener Example