Session In Spring Boot

_Bharti__Bharti_
2 min read

A session is like a memory that a web server uses to remember who you are.

When you log in to a website, the server creates a session for you. It helps you move between pages (like home, cart, profile) without logging in again and again.

Imagine you are shopping online

  • You log in once

  • Then go to different pages (cart, product details, orders)

  • You stay logged in the whole time

  • You add things to your cart — and they stay there

➡️ All this happens because of sessions.

Why Do We Need Sessions?

Without a session, the server wouldn’t remember who you are. So every time you open a new page, it would ask you to log in again. That’s not a good user experience.

Sessions help:

  • Keep users logged in

  • Store data like user ID, cart info, or roles

  • Maintain user state between requests

How Do Sessions Work?

  1. You log in → The server creates a session.

  2. The server stores your info (like username) in this session.

  3. A session ID is sent to your browser (in a cookie).

  4. When you visit other pages, your browser sends this session ID back.

  5. The server checks the ID and knows “Oh, it’s the same user!”

How to Use Sessions in Spring Boot

What is HttpSession in Spring Boot?

In Spring Boot, we use something called HttpSession to work with sessions. It is a built-in feature that helps store and retrieve data related to a specific user.

@PostMapping("/login")

public String login(@RequestParam String username, HttpSession session) {

session.setAttribute("username", username);//save the session

return "UserName "+username+" store in session";

}

Here, we can add username (which is dynamically take) into the session with the key "username".


    @GetMapping("/dashbord")
    public String dashboard(HttpSession session) {
        String userName=(String) session.getAttribute("username");//get session data
        if (userName == null) {
            return "Not found session detail.";
        }else
        return "Welcome "+userName;
    }

Here, we can check its really store in session or not.

@PostMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();//end the Session
        return "session ended";
    }

Here, we can end the session and also its makes sure no one else can use your session.

0
Subscribe to my newsletter

Read articles from _Bharti_ directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

_Bharti_
_Bharti_