Session In Spring Boot

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?
You log in → The server creates a session.
The server stores your info (like username) in this session.
A session ID is sent to your browser (in a cookie).
When you visit other pages, your browser sends this session ID back.
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.
Subscribe to my newsletter
Read articles from _Bharti_ directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
