Spring Boot + Session Management Example(2021) | CodeUsingJava

Spring Boot + Session Management Example(2021)

In this tutorial, we will learn about Spring Boot JDBC Session Management and learn how to implement the same.


Session management is the method used to securely manage various requests to a web-based service from an individual entity. HTTP is used to interact within webpages and browsers, and a session is a sequence of HTTP requests and events generated by the corresponding user. The session management implementation defines the means for distributing and constantly trading the session ID among the user and the web service.
As the HTTP protocol is stateless, we require session management to keep a record of user processes. Session Management is a web container framework applied to collect session data for a particular user. One of the following ways can be used to manage the session:
  • Cookies - this is the data sent from a webpage and is cached by the user's browser on their workstation as they browse.
  • Hidden form field - is the private data that will not be displayed to the user and is not modifiable.
  • URL Rewriting - is the process of altering the URL parameters.
  • HttpSession - allows data linkage with unique users.

User Sessions

Administering user sessions is essential in web services. We handle user session data in a batch environment by including a load balancer in the front of server nodes to allocate the traffic respectively.
In a dispersed environment, we control sessions in the methods provided below.
  • Sticky Session - The load balancer maps the requests of one client to a particular node. In case there is a node failure, the respective session is lost.
  • Session Replication - For a solution to the sticky session issue, the session replication format copies a session's information to various servers. In the event of a node failure, the particular session's data is retained by additional servers.
  • Session Data in a Persistent DataStore - Here, the session data is not stored in the server memory, it is stored in a database with a distinct ID to mark sessions called the SESSION_ID.

Spring Session Modules

The Spring Session is loaded with these modules:
  • Spring Session Core - core APIs
  • Spring Session Data Redis - Gives a session repository for a Redis database session administration.
  • Spring Session JDBC - Gives a session repository for a relational database (eg. MySQL) session administration.
  • Spring Session Hazelcast - Gives a session repository for the Hazelcast session administration.

Advantages of Spring Session

  • Spring Session separates the logic of session management from the created application, making it fault-tolerant.
  • Spring Session retains a user's session information in the database, which makes it ideal to implement in a clustered environment with various server nodes. For this, we do not require sticky session/session replication.
  • User session information is retained if the application malfunctions.
  • It is simple to shift among session storage software by changing configurations.
  • Spring, being an open-source project, is readily bootstrapped.

Session Management using Spring Boot Implementation

Here, we will be using HttpSession and the Spring Session JDBC Module for the implementation.
Session Management
No code is required to define the session objects to the MySQL server. We just use the property given below.
The Spring Session JDBC provides us with a Session-Repository implementation which is supported by a relational database (in our case, MySQL) and configuration support.
Session Management
Our project will look like this:

Session Management
The pom.xml file will be as follows:
<?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">



		<relativePath /> <!-- lookup parent from repository -->





The SpringBootSessionApplication.java file is as follows:
package com.codeusingjava;

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

public class SpringBootSessionApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSessionApplication.class, args);
Controller class creation:
package com.codeusingjava.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;

public class SpringBootJDBCController {

	public String home(Model model, HttpSession httpSession) {
		List<String> messages = (List<String>) httpSession.getAttribute("SPRING_BOOT_SESSION_MESSAGES");

		if (messages == null) {
			messages = new ArrayList<>();
		model.addAttribute("sessionMessages", messages);

		return "index";

	public String saveMessage(@RequestParam("msg") String message, HttpServletRequest httpServletRequest) {
		List<String> messages = (List<String>) httpServletRequest.getSession().getAttribute("SPRING_BOOT_SESSION_MESSAGES");
		if (messages == null) {
			messages = new ArrayList<>();
			httpServletRequest.getSession().setAttribute("SPRING_BOOT_SESSION_MESSAGES", messages);
		httpServletRequest.getSession().setAttribute("SPRING_BOOT_SESSION_MESSAGES", messages);
		return "redirect:/";

	public String deleteSession(HttpServletRequest httpServletRequest) {
		return "redirect:/";
In the above file, we are creating Array lists called SPRING_BOOT_SESSION_MESSAGES in the HttpSession along with Persist messages in the list.

The application.properties will be created as follows:


Create the index.html in the following manner:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8">
<title>Spring Boot Session Example</title>
		<form th:action="@{/saveMessage}" method="post">
			<textarea name="msg" cols="40" rows="2"></textarea>
			<br> <input type="submit" value="Save Message" />
		<h2>User Session</h2>
		<ul th:each="message : ">
			<li th:text="">msg</li>
		<form th:action="@{/delete}" method="post">
			<input type="submit" value="Delete Session" />
You can now compile and run the SpringBootSessionApplication.java file as a JAVA application. Navigate to localhost:8080 on a browser of your choice.
Session Management Output
There are two tables created in MySQL which will store the session's information.
Session Management Tables
Contents of spring_session table:
Session Management Table Display
Contents of spring_session_attributes table:
Session Management Table Display


Spring Boot JDBC Session Management Example