Sessions

suggest change

Because HTTP is inherently stateless, web applications rely on sessions to preserve user state—such as authentication credentials, user preferences, and shopping cart contents—across multiple consecutive requests.

In Java, session management encompasses both server-side state tracking (using the Jakarta Servlet HttpSession API and Spring Session) and client-side session persistence (using CookieManager with HttpClient).


1. Server-Side Session Management with HttpSession

The Jakarta Servlet specification provides the HttpSession interface to associate an arbitrary object map with a specific client browser.

When a server creates a new session, it issues a unique session token to the client inside a cookie named JSESSIONID. Subsequent browser requests automatically return this cookie, allowing the server to retrieve the client's session state.

Creating, Reading, and Invalidating Sessions

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/account")
public class UserAccountServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // false: Return the existing session if one exists, or null (do not create a new one)
        HttpSession session = req.getSession(false);

        if (session == null || session.getAttribute("CURRENT_USER") == null) {
            resp.sendRedirect("/login");
            return;
        }

        String username = (String) session.getAttribute("CURRENT_USER");
        resp.getWriter().println("Welcome back, " + username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        if ("login".equals(action)) {
            // true: Create a new session if none exists
            HttpSession session = req.getSession(true);

            // Store user identifier in the session
            session.setAttribute("CURRENT_USER", req.getParameter("username"));

            // Set session expiration timeout (in seconds: 1800s = 30 minutes)
            session.setMaxInactiveInterval(30 * 60);

            resp.getWriter().println("Logged in successfully");
        } else if ("logout".equals(action)) {
            HttpSession session = req.getSession(false);
            if (session != null) {
                // Destroy the session and unbind all stored attributes
                session.invalidate();
            }
            resp.getWriter().println("Logged out successfully");
        }
    }
}

2. Listening to Session Lifecycle Events

You can monitor session creation, destruction, and attribute modifications using HttpSessionListener:

import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

@WebListener
public class ActiveSessionTracker implements HttpSessionListener {

    private static final AtomicInteger activeSessions = new AtomicInteger(0);

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        int count = activeSessions.incrementAndGet();
        System.out.println("Session created: " + se.getSession().getId() + ". Total active: " + count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        int count = activeSessions.decrementAndGet();
        System.out.println("Session invalidated: " + se.getSession().getId() + ". Total active: " + count);
    }

    public static int getActiveSessionCount() {
        return activeSessions.get();
    }
}

3. Session Management in Spring Boot

In Spring MVC, you can access the session directly through method parameters or annotations:

package com.example.web;

import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CartController {

    @PostMapping("/cart/add")
    public String addToCart(@RequestParam String item, HttpSession session) {
        @SuppressWarnings("unchecked")
        java.util.List<String> cart = (java.util.List<String>) session.getAttribute("cart");
        if (cart == null) {
            cart = new java.util.ArrayList<>();
            session.setAttribute("cart", cart);
        }
        cart.add(item);
        return "redirect:/cart";
    }

    @GetMapping("/cart")
    public String viewCart(HttpSession session, Model model) {
        Object cart = session.getAttribute("cart");
        model.addAttribute("items", cart != null ? cart : java.util.Collections.emptyList());
        return "cartView";
    }
}

Distributed Sessions with Spring Session

In cloud and clustered environments, in-memory sessions are lost when traffic is balanced across multiple server nodes. Spring Session solves this by transparently backing HttpSession with external stores such as Redis:

<!-- In pom.xml -->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
# application.properties
spring.session.timeout=1800s
spring.data.redis.host=localhost
spring.data.redis.port=6379

With this configuration, any attribute added to HttpSession is automatically serialized and stored in Redis, enabling seamless failover and horizontal scaling.


4. Client-Side Session Handling with Java HttpClient

When writing a Java client application (or automated integration tests) that interacts with a session-based web service, you must manage cookies across requests so the server recognizes your session.

Java 11+'s HttpClient makes this easy with CookieManager:

import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SessionClientExample {
    public static void main(String[] args) throws Exception {
        // Create a CookieManager that retains all received cookies (including JSESSIONID)
        CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);

        HttpClient client = HttpClient.newBuilder()
                .cookieHandler(cookieManager)
                .build();

        // Step 1: Login request (server issues Set-Cookie: JSESSIONID=...)
        HttpRequest loginRequest = HttpRequest.newBuilder()
                .uri(URI.create("https://example.com/api/login"))
                .POST(HttpRequest.BodyPublishers.ofString("username=alice&password=secretPassword"))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .build();

        HttpResponse<String> loginResponse = client.send(loginRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println("Login Response: " + loginResponse.statusCode());

        // Step 2: Subsequent request automatically includes JSESSIONID cookie
        HttpRequest profileRequest = HttpRequest.newBuilder()
                .uri(URI.create("https://example.com/api/profile"))
                .GET()
                .build();

        HttpResponse<String> profileResponse = client.send(profileRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println("Profile Response:\n" + profileResponse.body());
    }
}

5. Security Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents