Open In App

Session Management in Java

Last Updated : 02 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Session Management is the process of tracking and storing user preferences and activities during their visit to a website or application. It helps maintain continuity until the user logs out or the session expires, avoiding the need to re-enter preferences repeatedly.

What is a Session?

A session stores user data on the server temporarily, starting when the user logs in and ending when they log out or close the browser. This data is accessible across different pages using a unique session ID and is securely stored in a format that can only be decoded by the server.

Why Session Management is Important

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 the specified value to the specified name in a particular session. This can be used to store data that needs to be managed across multiple requests.

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

2. getAttribute(String name)

Returns the value which is associated with the specified name in the particular session. This is used to retrieve previously stored session attributes.

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: The session is created when the user logs into the application for the initial time.
  • Action: The servlet container creates a new session for the user using HttpSession attribute when the user logs in the platform for the first time. As no existing session is associated with the user, it creates a new one and generates a session ID which is stored as a cookie on the client's browser based on the system requirements.

2. Attribute Setting

  • Trigger: Once the session is created, the required attributes are set on the session using the servlets or the JSP page.
  • Action: The required attribute are named and stored using the setAttribute method of the HttpSession object which makes sure that this can be use across multiple locations.

Example:

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

3. Client Interaction

  • Trigger: The user interacts with the web application, making additional requests.
  • Action: The session ID is now associated with each successive request, allowing the servlet container to map the request with the correct session. To retrieve the attributes associated to the particular session, use getAttribute method.

Example:

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

4. Session Invalidation

  • Trigger: The session can be invalidated explicitly by the application or automatically based on certain criteria as per the system requirements.
  • Action: We can invoke invalidate method to remove all the session attributes associated with that particular session. Further we can use a timeout concept which will invalidate the sessions automatically after a specified period of inactivity.

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();
    }
}

Explaination of the above Example:

  • A servlet named /api is created.
  • When a user accesses the servlet, the doGet method is called which retrieves the existing HttpSession associated with the request or creates a new one if it doesn't exist using the request.getSession() method.
  • The servlet sets a session attribute named "username" to the value "GFG" using session.setAttribute.
  • It retrieves the "username" attribute from the session using session.getAttribute and prints it in the HTTP response.
  • Finally, the session.invalidate() method is called to invalidate the session.

Practice Tags :

Similar Reads