Open In App

Spring Boot - Session Management

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Session management in Spring Boot is a critical aspect of web application development, especially when it comes to maintaining user state across multiple requests. HTTP is a stateless protocol, meaning each request from a client to the server is independent of any previous requests. To overcome this, session management allows the server to retain information about a client across multiple requests, thereby creating a session. This session can be used to track user activity, store preferences, and maintain security contexts. Spring Boot provides various mechanisms for managing sessions, including in-memory sessions, JDBC-based sessions, and Redis-based sessions.

In this article, we will walk through the basics of session management in Spring Boot, focusing on how to set up and manage user sessions efficiently.

Prerequisites

Before diving into session management in Spring Boot, ensure that you have the following prerequisites:

  • Java Development Kit 8 or higher: Required for Spring Boot applications.
  • Maven or Gradle: Dependency management for your Spring Boot project.
  • Basic Spring Boot knowledge: Understanding of how to build a Spring Boot application.
  • Spring Security: Knowledge of Spring Security for securing sessions.
  • IDE: Such as IntelliJ IDEA, Eclipse, or Spring Tool Suite.

HttpSession in Spring Boot

The HttpSession interface provided by the Servlet API allows developers to store and retrieve information about a user's session between HTTP requests. This is key in maintaining user-specific data like login information or shopping cart contents across multiple requests, despite HTTP being a stateless protocol.

Key Features of HttpSession

  • Session Creation and Management: Automatically creates and manages a session for each client.
  • Session ID: Each session is identified by a unique session ID stored on the client (usually as a cookie) and sent to the server with every HTTP request.
  • Attribute Storage: The session allows the storage of key-value pairs.
  • Session Timeout: Automatically invalidates a session after a defined period of inactivity.
  • Session Invalidation: Sessions can be manually invalidated for security or logout purposes.

Key Methods of HttpSession

  • getId(): Returns the unique session ID.
  • setAttribute(String name, Object value): Stores a session attribute.
  • getAttribute(String name): Retrieves the session attribute.
  • removeAttribute(String name): Removes a session attribute.
  • invalidate(): Invalidates the session.
  • getMaxInactiveInterval(): Gets the session timeout.
  • setMaxInactiveInterval(int interval): Sets the session timeout.

Session Management Approaches in Spring Boot

Spring Boot offers different methods for managing sessions:

  • In-Memory Sessions: Stores session data in the server’s memory.
  • JDBC-Based Sessions: Stores session data in a relational database.
  • Redis-Based Sessions: Stores session data in Redis, which allows for better scalability.
  • Session Cookies: Spring Boot uses cookies by default to store the session ID on the client side.

Spring Boot uses the HttpSession interface to manage sessions. When a session is created a unique session ID is generated and stored in a cookie on the client side. This session ID is then sent back to the server with each subsequent request to identify the session.

Here is a simple diagram to illustrate session management.

Session Management in Spring Boot

Steps to Implement Session Management in Spring Boot

First we need to create a sample spring boot application by using spring initializr with required dependencies. Once Project is created successfully then we configure the session management in application.properties file then we created API end points to test the session management in Spring Boot application. Below we provide step by step process for your reference.

Step 1: Create a Spring Boot Application

Using Spring Initializr, create a basic Spring Boot project with the following dependencies:

  • Spring Web
  • Thymeleaf (Optional)
  • Spring Boot DevTools (Optional)

To know how to create a Spring Boot application, read this article: How to Create a Spring Boot Project?

Project Dependencies:

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

The above dependencies are added to enable Spring Web for handling requests, Thymeleaf for template rendering (if required), and Lombok to simplify code.

Project Structure

After successfully creating the project, the folder structure will look like the below image.

Project Folder Structure


Step 2: Configure Session Management

Now, configure the session settings in the application.properties file.

application.properties:

spring.application.name=SessionManagement

# Default session timeout (in seconds)
server.servlet.session.timeout=600

# Enable JDBC session (if using JDBC)
# spring.session.store-type=jdbc

# Enable Redis session (if using Redis)
# spring.session.store-type=redis

# Configure session cookie
server.servlet.session.cookie.name=MY_SESSION_COOKIE
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true

Here, we set the session timeout to 600 seconds. The session ID is stored in a secure cookie that is HTTP-only. The session storage can be switched between in-memory, JDBC, or Redis depending on your needs.

Step 3: Create the Session Controller

Next, we create a SessionController to handle session creation, retrieval, and invalidation.

SessionController.java:

Java
package com.app;

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

import jakarta.servlet.http.HttpSession;

@RestController
@RequestMapping("/session")
public class SessionController {

    // Create a session and store an attribute
    @GetMapping("/create")
    public String createSession(HttpSession session) {
        // Set a session attribute (e.g., username)
        session.setAttribute("username", "JohnDoe");

        // Retrieve and return the session ID
        String sessionId = session.getId();
        return "Session created with ID: " + sessionId;
    }

    // Retrieve session attribute
    @GetMapping("/get")
    public String getSession(HttpSession session) {
        // Get the session attribute (username)
        String username = (String) session.getAttribute("username");

        // If no session exists, return an error message
        if (username == null) {
            return "No session found!";
        }

        // Return session data to the client
        return "Session found with username: " + username;
    }

    // Invalidate the session
    @GetMapping("/invalidate")
    public String invalidateSession(HttpSession session) {
        // Invalidate the session
        session.invalidate();
        return "Session invalidated!";
    }
}
  • createSession: Creates a new session and stores a username attribute. The session ID is returned to the client.
  • getSession: Retrieves the session and the username attribute.
  • invalidateSession: Invalidates the session, logging out the user.

Step 4: Run the Application

Run the Spring Boot application using your preferred IDE or command line. The application will run by default on port 8080 with the embedded Apache Tomcat server.

Application Running


Step 5: Testing the Session Management Endpoints

Once the application is running, you can test the session management API.

Create a Session

  • URL: http://localhost:8080/session/create
  • Expected Output: "Session created with ID: [session ID]"

This API end point is used for creating a session in the Spring Application. And this is GET mapping request. When you open this URL browser you got a message like session created with session id.

http://localhost:8080/session/create

Output:

session creation

Get Session Data

  • URL: http://localhost:8080/session/get
  • Expected Output: "Session found with username: JohnDoe" (if session exists)

This API end point is used for get session information in the Spring Application. And this is GET mapping request. When you open this URL browser you got a existing session details.

http://localhost:8080/session/get

Output:

get session

Invalidate a Session

  • URL: http://localhost:8080/session/invalidate
  • Expected Output: "Session invalidated!"
  • After invalidation, re-accessing the get endpoint will return "No session found!"

This API end point is used for invalidate the session information in the Spring Application. And this is GET mapping request. When you open this URL browser you got a existing session details will be invalidated.

http://localhost:8080/session/invalidate

Output:

session invalidated

Once session is invalidated then open the get session URL again you got session not found error message like below.

session not found

Conclusion

Session management in Spring Boot is simple and flexible. You can store sessions in-memory, in a database, or in Redis, depending on the scalability and distributed needs of your application. By following the steps outlined in this article, you can efficiently manage sessions in your Spring Boot applications.


Similar Reads