Spring Boot Session Management tutorial (2024) with Code Example | TechGeekNext


Spring Boot Session Management Example (2024)


Steps to implement Spring Boot Session Management, which will be covered in this tutorial.

  1. Create Spring Boot project from Spring Initializer.
  2. Add Spring Session jdbc dependency in pom.xml
  3. Add spring jdbc properties in application.properties
  4. Create rest end points to save, destroy/invalidate session.

What is Session Management?

Session management is the process of securely handling multiple requests to a web-based application or service from a single user or entity. HTTP is used to communicate between websites and browsers, and a session is a series of HTTP requests and transactions created by the same user. The session management implementation specifies the process for sharing and continually exchanging the session ID between the user and the web application.

Note : The full source code for Spring boot session management example can be downloaded at the end of this article.

You can also learn how to authenticate user using Spring Boot + JWT Token.



As HTTP protocol is stateless, and to keep track of customer behavior, we need session management. Session Management is a web container framework used to store session data for a specific user.

You can handle the session in one of the following ways-:

  1. A Cookies

    is a data sent from a website and saved by the user's web browser on the user's computer as the user browses.
  2. Hidden form field

    is a hidden data, which will not be shown to user and can not be modified. However, when the user submits the form, hidden data would be sent.
  3. URL Rewriting

    is the method of modifying the URL parameters.
  4. HttpSession

    enables data to be associated with individual visitors.

You may enhance your application's performance even further by storing static or frequently requested data in memory/cache provider. Refer Spring Boot Caching Example to learn more.

Managing user session is very important in most of the web applications. Mainly we have been maintaining user session data in cluster environment with load balancer in front of server nodes to distribute the traffic accordingly. So to manage the session environment like in production would be very crucial. In distributed environment, we can manage session in below ways.

  • Sticky Session

    In this type of session, load balancer would always route same client request to same node. But here if that node goes down, session would also be gone.
  • Session Replication

    To overcome sticky session problem, session replication replicates session data to multiple servers. So in case of any node goes down, session data would always be available with other nodes.
  • Session Data in a Persistent DataStore

    Here in this case session would not stored in server memory, instead, it will be store in database(RDBMS, Redis, HazelCast, MongoDB etc) with unique id called SESSION_ID.

If you want to do certain important tasks whenever an HTTP Session is created or deleted, use the Spring Boot + Session Listener Example.

Take a look at our suggested posts:



The following modules are included in the Spring Session:

  1. Spring Session Core

    - Spring Session core APIs
  2. Spring Session Data Redis

    - Provides session repository for Redis database session management
  3. Spring Session JDBC

    - Provides session repository for relational database like MYSQL etc session management.
  4. Spring Session Hazelcast

    - Provides session repository for Hazelcast session management.

By default Apache Tomcat store objects in memory for HTTP session management. Moreover, in order to manage Spring Boot Session Management, the HTTPSession will be used to store session information with persistent storage (Mysql) by using Spring Session JDBC.

In this tutorial, will see how to use Spring Boot Session Management using JDBC Session

(To achieve Spring Boot Session Management using Redis, refer this example.)

We don't have to write any code to write the session objects to MySQL server, as given below just use below property.

spring.session.store-type=jdbc
    

Spring Boot Session JDBC provides SessionRepository implementation backed by a relational database and configuration support.


Project will look as given below:


Create Spring Boot Rest Application



  • Go to Spring on official site https://start.spring.io/
  • Select Maven project, add dependencies
  • Click on Generate the project Button.
  • Import this generated project in Eclipse IDE as existing maven project and follow below steps.


Add Spring Session jdbc dependency in 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 https://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.8.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.techgeeknext</groupId>
	<artifactId>SpringBootSessionManagement</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootSessionManagement</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Create the Main Class

- SpringBootSessionManagementApplication
package com.techgeeknext;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootSessionManagementApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSessionManagementApplication.class, args);
	}
}

Create the Controller

to handle user request, process user's data and store the data in NOTES_SESSION attribute in session.
package com.techgeeknext.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class SpringBootSessionController {
    @PostMapping("/addNote")
    public String addNote(@RequestParam("note") String note, HttpServletRequest request) {
        //get the notes from request session
        List<String> notes = (List<String>) request.getSession().getAttribute("NOTES_SESSION");
        //check if notes is present in session or not
        if (notes == null) {
            notes = new ArrayList<>();
            // if notes object is not present in session, set notes in the request session
            request.getSession().setAttribute("NOTES_SESSION", notes);
        }
        notes.add(note);
        request.getSession().setAttribute("NOTES_SESSION", notes);
        return "redirect:/home";
    }
    @GetMapping("/home")
    public String home(Model model, HttpSession session) {
        List<String> notes = (List<String>) session.getAttribute("NOTES_SESSION");
        model.addAttribute("notesSession", notes!=null? notes:new ArrayList<>());
        return "home";
    }
    @PostMapping("/invalidate/session")
    public String destroySession(HttpServletRequest request) {
        //invalidate the session , this will clear the data from configured database (Mysql/redis/hazelcast)
        request.getSession().invalidate();
        return "redirect:/home";
    }
}

Add below configuration properties in application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springBootSession?createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
spring.session.timeout.seconds=600
spring.h2.console.enabled=true
                        
Create home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Session Management Example</title>
</head>
<body>
	<div>
		<form th:action="@{/addNote}" method="post">
			<textarea name="note" cols="40" rows="2"></textarea>
			<br> <input type="submit" value="Add Note" />
		</form>
	</div>
	<div>
		<form th:action="@{/invalidate/session}" method="post">
			<input type="submit" value="Destroy Session" />
		</form>
	</div>
	<div>
		<h2>Notes</h2>
		<ul th:each="note : ">
			<li th:text="">note</li>
		</ul>
	</div>

</body>
</html>

Our demo is ready, now compile and run the SpringBootSessionManagementApplication.java and go to home page http://localhost:8080/home.



Enter Note in Textarea and click on Add Note Button to add note in session


Go to home page, Note has been added to the session.

Add second Note in the session.



Now if you go to the database and see that the 2 tables will be created and the NOTE SESSION object will be stored in this table to manage the session.
  1. spring_session
  2. spring_session_attributes


Click on Destroy Session, Spring Boot will delete data (NOTES_SESSION) from spring_session_attributes table.


Now go to home page, session data got cleaned.

As you have seen how Spring boot store user session data to database, which will make very easy to maintain session data in cluster environment as well.

Download Source Code

The full source code for this article can be found on below.
Download it here - Spring Boot Session Management







Recommendation for Top Popular Post :