In this tutorial, we will learn about Http Session in Spring Boot and how to implement it in a project. Learn set session attributes and get attributes. How to use User session and authentication session. Learn session management and how to use it according to our need and purpose. Lets get started.

HttpSession - Spring Boot Session Management

A Simple Project: In this project, we have setup a simple spring boot project with thymeleaf, spring boot security and web. Find the initializr of this project here.

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>

About HttpSession

HttpSession provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

This interface allows servlets to

  • View and manipulate information about a session, such as the session identifier, creation time, and last accessed time
  • Bind objects to sessions, allowing user information to persist across multiple user connections

Following is the import statement:

import javax.servlet.http.HttpSession;

Example on Http Session in Spring Boot

In this example, we will set a session with name txId on in pageOne controller and get the session on PageTwo controller and check with a string, if match then remove the session attribute. If you see bellow, we are getting HttpSession parameter.

import javax.servlet.http.HttpSession;

@Controller
public class DemoController {
 
    @RequestMapping(value = "page-one", method = RequestMethod.GET)
    public String pageOne(HttpSession httpSession) {
        httpSession.setAttribute("txId", "tx1234");
        return "page-one";
    }

    @RequestMapping(value = "page-two", method = RequestMethod.GET)
    public String pageTwo(HttpSession httpSession) {
        String strCheck = "tx1234";
        String txIdSession = httpSession.getAttribute("txId").toString();
        if (txIdSession.equals(txId)) {
            httpSession.removeAttribute("txId");
        }
        return "page-two";
    }
}

In above example, we are using setAttribute, getAttribute and removeAttribute methods for setting, getting and removing session attributes respectively. There are bunch of different HttpSession Methods, you can check here.