Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 119 ยท Servlets and JSP

Sessions and Cookies

Learn how servlets remember users with HttpSession and cookies, set HttpOnly, Secure and SameSite correctly, prevent session fixation and log users out safely.

HTTP has no memory. Every request arrives on its own, and nothing in the protocol says "this is the same person who added a book to the cart a minute ago". Yet every shop, webmail and admin panel needs exactly that. The bridge is the cookie: a small piece of text the server asks the browser to store and send back with later requests. On top of cookies, servlet containers build sessions, a per-user storage area on the server that the cookie points to.

In this lesson you will watch cookies travel between a real server and client, build a session store by hand so nothing about HttpSession stays magic, and learn the cookie attributes that decide whether your login survives an attack. The servlet APIs are shown read-only; the runnable programs use the JDK's HttpServer and HttpClient, which speak the same HTTP. It helps to know how servlets read requests first.

A cookie is set by a response header and returned in a request header:

TEXT
HTTP/1.1 200 OK
Set-Cookie: theme=dark; Path=/; Max-Age=31536000; SameSite=Lax

GET /settings HTTP/1.1
Cookie: theme=dark

The server sends Set-Cookie (one header per cookie). The browser stores the cookie together with its attributes and, on every later request that matches them, sends all matching cookies back in a single Cookie header as name=value pairs separated by ; . The attributes themselves are never sent back. The server only learns names and values.

In a servlet you create and read cookies like this:

Java
Cookie theme = new Cookie("theme", "dark");
theme.setPath("/");
theme.setMaxAge(60 * 60 * 24 * 365);        // seconds; one year
theme.setAttribute("SameSite", "Lax");       // Servlet 6.0+
response.addCookie(theme);

Cookie[] cookies = request.getCookies();     // null when the request has no cookies!
if (cookies != null) {
    for (Cookie c : cookies) {
        if (c.getName().equals("theme")) { /* use c.getValue() */ }
    }
}

Note that getCookies() returns null, not an empty array, when there are none: a classic NullPointerException source. Also keep values simple. Spaces, commas, semicolons and quotes are not allowed in cookie values under RFC 6265, and Tomcat rejects them, so URL-encode or Base64url-encode anything unusual.

The next program runs a server that counts visits in a cookie. One client has a cookie store (CookieManager), like a browser. A second client has none, and a third one forges the cookie by hand.

Java A visit counter stored in a cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first client's count goes up, because its cookie store sends visits back each time. The second client stays at visit #1 forever: without cookies, every request is a stranger. The third shows the most important lesson about cookies: the client controls them. A server that stored isAdmin=true or a price in a cookie would believe whatever the user typed. Cookies are fine for harmless preferences, but anything that matters must live on the server, with only an unguessable key in the cookie. That key is the session ID.

HttpSession: state on the server

A session is a map of attributes that the container keeps on the server for one browser. The container generates a long random ID, stores the session under it and sends the ID in a cookie, named JSESSIONID by default. On later requests it reads the cookie, finds the session and hands it to your code.

Java
HttpSession session = request.getSession();          // existing session, or create a new one
HttpSession maybe = request.getSession(false);       // existing session, or null

session.setAttribute("cart", cart);
Cart cart = (Cart) session.getAttribute("cart");
session.removeAttribute("couponCode");

session.getId();                  // the ID sent in the cookie
session.isNew();                  // true until the client has sent the ID back once
session.setMaxInactiveInterval(15 * 60);   // seconds of inactivity before it expires
session.invalidate();             // destroy it now (logout)

Use getSession(false) on pages that only read session data. Calling getSession() on every page creates a session (and a cookie, and server memory) for every visitor and every search-engine crawler, even those who never log in.

Here is the idea built by hand on HttpServer: a session store with secure random IDs, a cart that works for guests, a login that keeps the cart, and a logout. The comments mark where a servlet would call getSession, changeSessionId and invalidate.

Java A hand-made session store with login and logout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from top to bottom. The first /cart creates nothing, because it only reads. Adding a book creates a session for the guest. Logging in keeps the cart but changes the session ID. Logout destroys the session on the server and tells the browser to delete the cookie with Max-Age=0, and an attacker who copied the old ID gets nothing. Real containers work the same way, plus expiry, which you'll see shortly.

Session fixation and why the ID must change at login

In a session fixation attack, the attacker gets a valid session ID from your site (just by visiting it) and tricks the victim into using it, for example through a link on an old server that accepts ;jsessionid= in URLs. When the victim logs in, the session the attacker knows the ID of is now a logged-in session. The defense is the one you just saw: give the session a new ID at every privilege change, especially login.

Java
// after the password has been verified
request.changeSessionId();                 // Servlet 3.1+: keeps attributes, new ID
request.getSession().setAttribute("user", user);

Frameworks such as Spring Security do this automatically, but in plain servlet code it's your job.

You configure the container's session handling in web.xml:

XML
<session-config>
    <session-timeout>30</session-timeout>              <!-- minutes of inactivity -->
    <cookie-config>
        <name>SID</name>                                <!-- default is JSESSIONID -->
        <http-only>true</http-only>
        <secure>true</secure>
        <attribute>                                     <!-- Servlet 6.0+ -->
            <attribute-name>SameSite</attribute-name>
            <attribute-value>Lax</attribute-value>
        </attribute>
    </cookie-config>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>

<tracking-mode>COOKIE</tracking-mode> matters more than it looks. Without it, a container may fall back to URL rewriting when a browser refuses cookies, appending ;jsessionid=... to links produced by response.encodeURL(). Session IDs in URLs end up in browser history, server logs, bookmarks and Referer headers sent to other sites, and they make fixation trivial. Turn it off.

Every attribute narrows when and where the browser sends a cookie or what scripts can do with it:

Attribute Effect Recommendation
Max-Age=n / Expires=date lifetime; without either, the cookie is a session cookie deleted when the browser closes; Max-Age=0 deletes it session IDs: no Max-Age; preferences: long
Path=/ only sent for URLs under this path usually / or the context path
Domain=example.com also sent to subdomains; without it, only the exact host leave it out unless you need subdomains
Secure only sent over HTTPS always in production
HttpOnly invisible to JavaScript (document.cookie) always for session cookies
SameSite=Strict/Lax/None whether the cookie is sent on requests started by other sites Lax for sessions; None requires Secure

HttpOnly limits the damage of cross-site scripting (XSS): if an attacker manages to run JavaScript in your page, it still can't read the session ID and send it home. SameSite is the main defense against cross-site request forgery (CSRF): with Lax, a form on an evil site that posts to your bank does not carry the bank's session cookie, while ordinary links from other sites still log the user in as expected. Strict is safer but means users arriving from a link in an email appear logged out. Modern browsers treat cookies without SameSite as Lax. The Web Security Basics lesson covers XSS and CSRF in more depth.

Two name prefixes make browsers enforce rules: a cookie named __Secure-... is only accepted with Secure, and __Host-... additionally requires Path=/ and no Domain, which pins it to one exact host.

The next program sets four cookies with different attributes and then shows which ones the client sends back to two different paths. Java's CookieManager applies the same rules as a browser for Path, Secure and Max-Age.

Java Which cookies does the client send back?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

promo never even made it into the store: Max-Age=0 means "delete now", which is exactly how you remove a cookie (send it again with the same name, path and domain, and a zero lifetime). token is stored but never sent, because the connection is plain HTTP and the cookie is Secure. adminTab only travels to URLs under /admin. Only theme goes everywhere, and it is the only persistent one: the others have no lifetime, so a browser would drop them when it closes.

java.net.CookieManager predates today's cookie standard (RFC 6265). When a cookie has Max-Age, it switches to an obsolete format and sends values back as $Version="1"; theme="dark", which most servers don't expect. That is why these demos use Expires for lifetimes. Browsers and the servlet Cookie class handle Max-Age correctly.

Session timeouts and memory

Sessions live in server memory, so the container must eventually throw them away. The inactivity timeout (30 minutes by default in Tomcat) is a sliding window: every request that uses the session resets the clock. Some applications add an absolute timeout too, for example "log out after 12 hours no matter what", which you implement by storing the login time in the session and checking it in a filter.

The program below models a sliding timeout with a fake clock, so you can see which requests keep the session alive and which arrive too late.

Java Sliding session timeout with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Session A survives a 25-minute pause because each visit restarted the 30-minute window, then expires after a 31-minute gap. Session B is never idle for long, but the absolute two-hour limit ends it at 11:05.

Memory is the other cost. Every attribute you store is multiplied by the number of active users. Keep sessions small: store a user ID rather than the whole user with their order history, and never cache large query results there. If you run several servers behind a load balancer, either use sticky sessions (the balancer sends each user to the same server), let the container replicate sessions, or move them to a shared store such as Redis (Spring Session does this). In the last two cases every attribute must be Serializable.

Logging out properly

A complete logout does four things:

Java
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();                          // 1. destroy server-side state
        }
        Cookie remember = new Cookie("remember-me", "");   // 2. delete other auth cookies
        remember.setPath("/");
        remember.setMaxAge(0);
        response.addCookie(remember);
        response.setHeader("Cache-Control", "no-store");   // 3. keep private pages out of caches
        response.sendRedirect(request.getContextPath() + "/"); // 4. Post/Redirect/Get
    }
}

Use POST for logout, not a plain link: otherwise any page could log your users out with an <img src="/logout">. After invalidate(), calling getAttribute on that session object throws IllegalStateException, so don't touch it again in the same request.

Sessions vs tokens

Sessions are stateful: the server remembers each user. Many APIs instead use stateless tokens such as JWTs, where the signed token itself carries the user's identity and the server stores nothing. Tokens scale easily across servers but are hard to revoke before they expire; sessions are easy to revoke but need shared storage at scale. For classic server-rendered web apps, sessions with secure cookies remain the simplest and safest choice. You'll build and verify a token in JWT and OAuth 2.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A server sends Set-Cookie with role=admin. Why is it a bad idea to trust that cookie on later requests?

    Cookies are stored and sent by the client, which can change or forge them freely. Keep important state on the server and put only a random session ID in the cookie.
  2. 2. What does request.getSession(false) return when the request has no valid session?

    With false, the container never creates a session. It returns null, which lets read-only pages avoid creating sessions for every visitor.
  3. 3. Which cookie attribute stops JavaScript running in your page from reading the session ID?

    HttpOnly hides the cookie from document.cookie, which limits the damage of an XSS bug. Secure controls HTTPS-only sending, and SameSite controls cross-site requests.
  4. 4. Why should the session ID change right after a successful login?

    This defends against session fixation. changeSessionId() keeps the attributes but gives the session a fresh, unknown ID.
  5. 5. The session timeout is 30 minutes. A user makes requests at 9:00, 9:25 and 9:50. Is the session still valid at 9:50?

    The inactivity timeout is a sliding window. Each request resets it, so only gaps longer than 30 minutes end the session.

Summary

  • Servers set cookies with Set-Cookie; browsers return matching ones in the Cookie header. Only names and values come back, and the client can change them at will.
  • HttpSession keeps per-user data on the server, identified by a random ID in a cookie (JSESSIONID by default). Use getSession(false) when you only read.
  • Call request.changeSessionId() after login to prevent session fixation, and disable URL rewriting with <tracking-mode>COOKIE</tracking-mode>.
  • Session cookies should be HttpOnly, Secure and SameSite=Lax (or Strict); configure them in <cookie-config>.
  • Delete a cookie by sending it again with Max-Age=0 and the same path and domain.
  • Sessions expire after inactivity (a sliding window); keep them small and Serializable if they're shared between servers.
  • Log out with a POST that invalidates the session, deletes auth cookies and redirects.

Next: Filters and Listeners shows how to run code around every request, for example to check that a session belongs to a logged-in user.