Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Servlets · Lesson 6

Cookies in Servlets

What Cookies Do

A cookie is a small name-value pair that a browser sends back to a server on matching requests. Servlets use cookies for preferences, correlation identifiers, and limited client-side state. Cookies are not a replacement for secure server-side session storage.

The Cookie API lets a servlet set attributes such as its path, lifetime, and security flags. Always treat a cookie value as untrusted input because the client can change it.

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

public class ThemeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Cookie themeCookie = new Cookie("theme", "dark");
        themeCookie.setMaxAge(60 * 60 * 24 * 30);
        themeCookie.setPath(request.getContextPath());
        themeCookie.setHttpOnly(true);
        themeCookie.setSecure(request.isSecure());
        response.addCookie(themeCookie);

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Theme preference saved");
    }
}
AttributeEffectTypical reason
Max-AgeControls lifetimePersistent preference
PathLimits request pathsScope a cookie to an application
HttpOnlyBlocks most script accessReduce cookie theft through scripts
SecureSends only over HTTPSProtect transport
SameSiteLimits cross-site sendingReduce CSRF exposure

Common Mistake and Practices

Common Mistake: Putting passwords, authorization decisions, or unencrypted personal data directly in a cookie. Clients can inspect and modify cookie values, even when the cookie is marked HttpOnly.

  • Use HttpOnly and Secure where appropriate.
  • Keep cookie values short and non-sensitive.
  • Set an explicit path and lifetime.
  • Validate values before using them.
  • Prefer a server-side session for confidential state.

Real-World Use Case

A learning platform stores a non-sensitive theme preference in a cookie so the interface can restore dark or light mode on a later visit. The account and progress data remain on the server behind the authenticated session.

Quiz Check

Quick Knowledge Test

Loading quiz questions...