Session Management in Java

Last Updated : 18 Apr, 2026

Session Management in Java is used to maintain user-specific data across multiple requests in a web application. Since HTTP is stateless, it helps preserve user state between interactions. It ensures continuity until the session expires or the user logs out.

  • Common techniques include Cookies, URL Rewriting, Hidden Fields, and HttpSession.
  • It improves user experience by preserving login status and preferences.
  • Essential for handling authentication and personalized content delivery.

Session

A Session is a server-side mechanism used to store user data across multiple requests in a web application. It helps maintain user state and ensures continuity during interaction.

  • Automatically created when a user interacts with the application.
  • Identified using a unique session ID stored on the client side.
  • Expires after inactivity or when explicitly invalidated.

Importance Of Session Managements

Session management is essential for both functionality and security in web applications. Here's why:

  • It securely stores user credentials (often encrypted) to support features like auto-login.
  • Sensitive data can be stored safely due to encryption.
  • Sessions allow faster response times by quickly accessing temporary data.
  • They help restrict access from unauthorized sources, enhancing application and network security.

Role of Cookies and Other Tracking Mechanisms

Cookies and tracking mechanisms are essential for session management. They help websites recognize users, store preferences and ensure secure, personalized experiences.

1. Session Cookies

  • Purpose: Manage temporary session data like login status.
  • How it works: A unique session ID is created and stored in a cookie when the user logs in.
  • Expiry: Automatically deleted when the browser is closed.
  • Use: Supports auto-login during a session without re-entering credentials.

2. Persistent Cookies

  • Purpose: Store user preferences and settings long-term.
  • How it works: Remains stored on the user’s device even after the browser is closed.
  • Use: Enables personalized experiences across multiple visits.

3. Tracking Mechanisms

  • User Tracking: JavaScript or tracking pixels monitor user behavior for analytics and improved UX.
  • Third-Party Cookies: Set by external domains for cross-site tracking and targeted advertising.

4. Security Measures

  • CSRF Tokens: Prevent unauthorized actions by storing anti-CSRF tokens in cookies.
  • Secure & HttpOnly Flags:
  • Secure: Ensures cookies are only sent over HTTPS.
  • HttpOnly: Prevents client-side scripts from accessing the cookie, reducing attack risks.

How to Get a Session?

  • In Java Servlets, sessions are managed using the HttpSession object.
  • HttpSession is part of the javax.servlet.http package.
  • It allows tracking the client's session and storing user information.
  • Used to store and retrieve attributes across multiple client requests.
  • Helps manage session state and user data efficiently.

Retrieving HttpSession in Servlets

1. Use request.getSession() to get the current session or create a new one if it doesn't exist.

HttpSession session = request.getSession();

2. Use request.getSession(true) to force creation of a new session if none exists.

HttpSession session = request.getSession(true);

3. Use request.getSession(false) to fetch an existing session only (returns null if none exists).

HttpSession session = request.getSession(false);

Common Methods

1. setAttribute(String name, Object value)

This Associates a value with a name in the session, allowing data to be stored and accessed across multiple requests.

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

2. getAttribute(String name)

Returns the value associated with the specified name in the session, used to retrieve previously stored data.

HttpSession session = request.getSession(); String username = (String) session.getAttribute("username");

3. removeAttribute(String name)

It removes the attribute with the specified name from the session.

HttpSession session = request.getSession(); session.removeAttribute("username");

4. invalidate()

Once the services are completed, it is necessary to destroy the session object. The syntax follows.

HttpSession session = request.getSession(); session.invalidate();

Example

Java
import javax.servlet.http.*;

@WebServlet("/api")
public class GFG extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        // Retrieve the HttpSession object
        HttpSession session = request.getSession();

        // Use HttpSession methods
        session.setAttribute("username", "GFG");
        String value = (String) session.getAttribute("username");
    }
}

Explanation: In the above example, the getSession() method is called on the HttpServletRequest object to retrieve the HttpSession. Once you have the HttpSession object, you can use its methods to set and retrieve session attributes.

Session Tracking Mechanisms in Servlets

To maintain the session between a web server and a web client, following methods can be used.

1. Cookies

  • The server assigns a unique session ID to the client in the form of a cookie.
  • On subsequent requests, the client sends this cookie, helping the server identify the session.
  • This approach is browser-dependent and may not work if cookies are disabled or blocked.
  • Syntax example:

Cookie cookie = new Cookie("sessionId", "123456");
response.addCookie(cookie);

2. Hidden Form Fields

  • The server embeds a hidden input field with a session ID in the HTML form:

<input type = "hidden" name = "sessionId" value = "12345">

  • This sends the session ID with each form submission, allowing the server to track the session.
  • It works only with form submissions, not with standard hyperlinks (<a href="">), Hence, it’s not suitable for general session tracking.

3. URL Rewriting

  • The session ID is appended to the URL as a query parameter.
  • This helps the server identify the session and process the client’s request.
  • Works independently of browser settings (unlike cookies).
  • Not suitable for static pages as URLs are generated dynamically.

Example:

String urlWithSessionId = response.encodeURL("/api");

Session Lifecycle

The stages which a user session goes through right from its creation to its eventual expiration completes the session lifecycle. In the context of web applications, the lifecycle involves the management of user-specific data across multiple session requests. The key stages involved in the session lifecycle are described below.

1. Session Creation

  • Trigger: Session is created when the user logs in for the first time.
  • Action: Server creates a new HttpSession, generates a unique session ID, and stores it (usually as a cookie) in the client’s browser.

2. Attribute Setting

  • Trigger: After session creation, required attributes are added.
  • Action: Attributes are stored using setAttribute() of HttpSession, making them accessible across multiple requests.

Example:

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

3. Client Interaction

  • Trigger: User makes additional requests while interacting with the application.
  • Action: Session ID is sent with each request, allowing retrieval of data using getAttribute().

Example:

HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");

4. Session Invalidation

  • Trigger: Session ends manually or after inactivity timeout.
  • Action: invalidate() removes all session data, or it expires automatically after a set time.

HttpSession session = request.getSession(); session.invalidate();

5. Session Expiration

  • Trigger: We can set the session timeout, which is a defined maximum time of existence.
  • Action: Once the browsing is completed, we can remove the data and the user's preference based on the maximum inactive time interval.

HttpSession session = request.getSession();
// Session will be invalidated after 30 minutes of inactivity session.setMaxInactiveInterval(1800);

Example of Session Management

Below example demonstrates creating a session, setting and retrieving attributes and finally, invalidating the session.

Java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/api")
public class GFG extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get the HttpSession object. If it doesn't exist, a new one will be created.
        HttpSession session = request.getSession();

        // Set a session attribute
        session.setAttribute("username", "GFG");

        // Retrieve the session attribute
        String username = (String) session.getAttribute("username");

        // Display the attribute value in the response
        response.getWriter().println("Username from Session: " + username);
        
        // Invalidate the session after displaying the attribute
        session.invalidate();
    }
}

Explanation: A servlet /api handles the request using doGet() and creates or retrieves the session using request.getSession(). It stores and fetches the "username" attribute, displays it in the response, and finally invalidates the session using invalidate().

Comment