Spring Boot + Session Management Example(2024) | CodeUsingJava








Spring Boot + Session Management Example(2024)

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

Introduction

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.
spring.session.store-type=jdbc
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">
    <modelVersion>4.0.0</modelVersion>

	<groupId>com.codeusingjava</groupId>
	<artifactId>Spring-Boot-Session-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Spring-Boot-Session-Example</name>
	<description>Spring-Boot-Session-Example</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>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>

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

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

@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;

@Controller
public class SpringBootJDBCController {

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

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

		return "index";
	}

	@PostMapping("/saveMessage")
	public String saveMessage(@RequestParam("msg") String message, HttpServletRequest httpServletRequest) {
		@SuppressWarnings("unchecked")
		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);
		}
		messages.add(message);
		httpServletRequest.getSession().setAttribute("SPRING_BOOT_SESSION_MESSAGES", messages);
		return "redirect:/";
	}

	@PostMapping("/delete")
	public String deleteSession(HttpServletRequest httpServletRequest) {
		httpServletRequest.getSession().invalidate();
		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.

HttpSession
The application.properties will be created as follows:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/springSession
spring.datasource.username=root
spring.datasource.password=tiger

spring.h2.console.enabled=true

spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
spring.session.timeout.seconds=900
Create the index.html in the following manner:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Session Example</title>
</head>
<body>
	<div>
		<form th:action="@{/saveMessage}" method="post">
			<textarea name="msg" cols="40" rows="2"></textarea>
			<br> <input type="submit" value="Save Message" />
		</form>
	</div>
	<div>
		<h2>User Session</h2>
		<ul th:each="message : ">
			<li th:text="">msg</li>
		</ul>
	</div>
	<div>
		<form th:action="@{/delete}" method="post">
			<input type="submit" value="Delete Session" />
		</form>
	</div>
</body>
</html>
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

Downloads-

Spring Boot JDBC Session Management Example