Hackforge Academy

Category: java

Session management cookies httpsession

Published on 30 Sep 2026

Explanation

HTTP is stateless, so session management is required when an application needs to remember information about a user across multiple requests.

Code:

Request 1 β†’ Login
Request 2 β†’ Dashboard
Request 3 β†’ Profile

Session keeps user information available across requests.

Explanation

A cookie is a small piece of data stored by the browser and sent back to the server with subsequent requests.

Code:

Cookie cookie = new Cookie("username", "Praveen");
response.addCookie(cookie);

Explanation

Read cookies from an incoming request using getCookies().

Code:

Cookie[] cookies = request.getCookies();

if (cookies != null) {
    for (Cookie cookie : cookies) {
        System.out.println(cookie.getName());
    }
}

Explanation

HttpSession stores server-side information associated with a particular user session.

Code:

HttpSession session = request.getSession();
session.setAttribute("username", "Praveen");

Explanation

Retrieve and remove session attributes using getAttribute() and removeAttribute().

Code:

String username =
    (String) session.getAttribute("username");

session.removeAttribute("username");

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community