Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Servlets · Lesson 5

Session Management

What a Session Is

A session lets a server associate several HTTP requests with one user or browser. HTTP is stateless, so a servlet container uses a session identifier to recover server-side state between requests. Session state is useful for carts, sign-in state, and short-lived preferences.

Creating and Reading Sessions

HttpServletRequest.getSession() returns the current session or creates one when necessary. Store small, serializable values with clear names and remove them when the workflow ends.

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

public class CartServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String productCode = request.getParameter("productCode");
        HttpSession session = request.getSession();
        Integer itemCount = (Integer) session.getAttribute("itemCount");
        int updatedCount = itemCount == null ? 1 : itemCount + 1;
        session.setAttribute("itemCount", updatedCount);
        response.getWriter().println("Added " + productCode + "; items: " + updatedCount);
    }
}

Session Operations

OperationServlet APIPurpose
Start or accessgetSession()Create or retrieve a session
Read stategetAttribute()Get a stored value
Write statesetAttribute()Store a value
Remove valueremoveAttribute()Clear one item
End sessioninvalidate()Discard all session state

Security and Common Mistake

Common Mistake: Keeping sensitive authentication data or large objects in the session without an expiration plan. A session is server memory, and stale sessions can become both a security and capacity problem.

  • Set a reasonable inactivity timeout.
  • Invalidate the session during logout.
  • Regenerate the session identifier after login when supported by the container.
  • Store identifiers rather than large domain graphs.
  • Avoid trusting session values without authorization checks.

Real-World Use Case

An online store stores a cart identifier and item count in the session while a shopper moves between product pages. At checkout, the application loads the cart from durable storage and invalidates temporary checkout state after payment.

Quiz Check

Quick Knowledge Test

Loading quiz questions...