1. Overview

This article contains Spring Boot Session Listener Example or Spring boot HttpSessionListener as well as HttpSessionAttributeListener. To create Http Session Listener need to create @Bean of  HttpSessionListener class and to create @Bean of HttpSessionAttributeListener for http Session attribute listener.

HttpSessionListener has two methods sessionCreated(called when session created) and sessionDestroyed (called when session destroyed)

HttpSessionAttributeListener has three methodsattributeAdded (called when new attribute add to session), attributeRemoved (called when attribute remove from the session), attributeReplaced(called when session attribute replace or updated)

2. Example

Spring Boot Session Listener Example

Spring Boot Session Listener Example

2.1 pom.xml

<?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>

    <groupId>spring-boot-example</groupId>
    <artifactId>spring-boot-session-listener-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>Spring boot session listener example</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>         <!--its for spring mvc related -->
            <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>

2.2 HttpSessionConfig

We have created two beans here HttpSessionListener for session listener and HttpSessionAttributeListener for session attribute listener:

package com.javadeveloperzone;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


/**
 * Created by JavaDeveloperZone on 13-11-2017.
 */
@Configuration
public class HttpSessionConfig {

    @Bean                           // bean for http session listener
    public HttpSessionListener httpSessionListener() {
        return new HttpSessionListener() {
            @Override
            public void sessionCreated(HttpSessionEvent se) {               // This method will be called when session created
                System.out.println("Session Created with session id+" + se.getSession().getId());
            }

            @Override
            public void sessionDestroyed(HttpSessionEvent se) {         // This method will be automatically called when session destroyed
                System.out.println("Session Destroyed, Session id:" + se.getSession().getId());

            }
        };
    }

    @Bean                   // bean for http session attribute listener
    public HttpSessionAttributeListener httpSessionAttributeListener() {
        return new HttpSessionAttributeListener() {
            @Override
            public void attributeAdded(HttpSessionBindingEvent se) {            // This method will be automatically called when session attribute added
                System.out.println("Attribute Added following information");
                System.out.println("Attribute Name:" + se.getName());
                System.out.println("Attribute Value:" + se.getName());
            }

            @Override
            public void attributeRemoved(HttpSessionBindingEvent se) {      // This method will be automatically called when session attribute removed
                System.out.println("attributeRemoved");
            }

            @Override
            public void attributeReplaced(HttpSessionBindingEvent se) {     // This method will be automatically called when session attribute replace
                System.out.println("Attribute Replaced following information");
                System.out.println("Attribute Name:" + se.getName());
                System.out.println("Attribute Old Value:" + se.getValue());
            }
        };
    }
}

2.3 SpringBootConfig

package com.javadeveloperzone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */

@SpringBootApplication
@ComponentScan
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
}

2.4 SessionDemoController

Please read comments in the code for more explanation:

package com.javadeveloperzone.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@RestController
public class SessionDemoController {

    @GetMapping("/viewSessionData")                     // it will handle all request for /viewSessionData
    public java.util.Map<String, Integer> start(HttpServletRequest request) {
        Integer integer = (Integer) request.getSession()
                                           .getAttribute("hitCounter");        // create session if not exists and get attribute
        if (integer == null) {
            integer = new Integer(0);
            integer++;
            request.getSession().setAttribute("hitCounter", integer);           // replace session attribute
        } else {
            integer++;
            request.getSession().setAttribute("hitCounter", integer);            // replace session attribute
        }
        java.util.Map<String, Integer> hitCounter = new HashMap<>();
        hitCounter.put("Hit Counter", integer);
        return hitCounter;
    }

}

2.5 Build Application

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-session-listener-example 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ spring-boot-session-listener-example ---
[INFO] Deleting F:\extrawork\spring-boot\spring-boot-session-listener-example\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.464 s
[INFO] Finished at: 2017-12-16T19:06:51+05:30
[INFO] Final Memory: 9M/184M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

2.6 Run Application

mvn install

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

PID 76044 (F:\extrawork\spring-boot\spring-boot-session-listener-example\target\classes started by Lenovo in F:\extrawork\spring-boot\spring-boot-session-listener-example)
2017-12-16 19:09:08.958  INFO 76044 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/viewSessionData],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Integer> com.javadeveloperzone.controller.SessionDemoController.start(javax.servlet.http.HttpServletRequest)
2017-12-16 19:09:08.964  INFO 76044 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-16 19:09:08.964  INFO 76044 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-16 19:09:09.019  INFO 76044 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 19:09:09.020  INFO 76044 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 19:09:09.095  INFO 76044 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 19:09:09.458  INFO 76044 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-12-16 19:09:09.559  INFO 76044 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-16 19:09:09.566  INFO 76044 --- [           main] com.javadeveloperzone.SpringBootConfig   : Started SpringBootConfig in 6.1 seconds (JVM running for 7.085)

Output:

http://localhost:8080/viewSessionData when calling 1st time

Spring Boot Session Listener Example - output 1

Spring Boot Session Listener Example – output 1

Log:

Session Created with session id:D05B374CDBC2C48E678E8F0A4238A70F
Attribute Added following information
Attribute Name:hitCounter
Attribute Value:hitCounter

http://localhost:8080/viewSessionData when calling 2nd time

Spring Boot Session Listener Example - output 2

Spring Boot Session Listener Example – output 2

Attribute Replaced following information
Attribute Name:hitCounter
Attribute Old Value:1

 

3. References

4. Source Code

Spring Boot Session Listener Example.zip (44 KB)

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *