Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How does the servlet container track a user session, and which cookie attributes should be set for security?

The servlet container gives each user a random session id, usually sent in a cookie named JSESSIONID, and keeps the session data itself on the server under that id. For security the cookie should be HttpOnly, Secure and have a suitable SameSite value, and the application must give the user a new session id right after login so an attacker cannot fix the id in advance.

Why this question is asked

HTTP is stateless: every request arrives on its own, and the server has no built-in idea that two requests came from the same person. Sessions are how a web application remembers a logged-in user or a shopping basket between requests, and the session cookie is effectively the user's key to that state. Interviewers ask this because a weak session cookie is one of the easiest ways to lose an account to an attacker. In this answer, we will see how the container creates and finds a session, what each cookie attribute protects against, how session fixation works and how to stop it, and how to set all of this in Spring Boot.

1A Quick Recap of HTTP Sessions

A session is a small piece of server-side memory that belongs to one user. In the Servlet API we reach it with request.getSession(), which returns an HttpSession object. We can store attributes in it, such as the current user or a cart, and read them back on the next request.

The container (Tomcat, Jetty or another servlet engine) has to recognise which session a request belongs to. It does this with a session id, a long random string. The data stays on the server; only the id travels to the browser. That split matters: the browser never sees the cart or the user's roles, only an opaque key that points to them.

2How the Container Tracks a Session

The first time code calls request.getSession(), the container generates a new random id, creates an empty session in its session store (by default an in-memory map) and adds a Set-Cookie header to the response with a cookie named JSESSIONID. The browser stores the cookie and sends it back on every later request to the same site.

On the next request the container reads the JSESSIONID cookie, looks up the id in its store and hands our code the same HttpSession. If the cookie is missing or the session has expired (Tomcat's default timeout is 30 minutes of inactivity), getSession() creates a fresh one. Containers can also fall back to URL rewriting, adding ;jsessionid=... to links, but that leaks the id into logs and browser history, so modern applications turn it off.

Java
HttpSession session = request.getSession(); // creates one if absent
session.setAttribute("cartId", 42L);
// Response header on the first request:
// Set-Cookie: JSESSIONID=8F3A...C1; Path=/; HttpOnly
// Next request from the browser:
// Cookie: JSESSIONID=8F3A...C1
Long cartId = (Long) request.getSession().getAttribute("cartId"); // 42
Step throughCreating and finding a session
BrowserContainerSession store
GET /cart (no cookie)
create session with new random id
Set-Cookie: JSESSIONID=8F3A...
GET /cart, Cookie: JSESSIONID=8F3A...
look up 8F3A...
same HttpSession

6 messages in order. Play them, or step through them one at a time.

Only the id goes to the browser; the data stays on the server.

3The Cookie Attributes That Protect the Session

Because the session id is the whole key, anyone who learns it becomes the user. Each cookie attribute closes one way of stealing or misusing it.

HttpOnly tells the browser not to let JavaScript read the cookie through document.cookie. If an attacker manages to inject a script into our page (cross-site scripting), the script still cannot copy the session id and send it away. Secure tells the browser to send the cookie only over HTTPS, so it never travels in plain text over a coffee-shop network.

SameSite controls whether the browser sends the cookie on requests that start from another site. With SameSite=Lax, the cookie goes along when a user clicks a link to our site but not when another site silently posts a form to us, which is the core of a cross-site request forgery (CSRF) attack. Strict is tighter and drops the cookie even on cross-site links, which can make users look logged out when they arrive from an email. None allows all cross-site sending and must be combined with Secure. Lax is a good default for most applications, but it reduces CSRF risk rather than removing it, so CSRF tokens are still worth keeping for state-changing requests.

Session cookie attributes
AttributeProtects againstTypical value
HttpOnlyScripts stealing the id after an XSS bugAlways on
SecureThe id travelling over plain HTTPOn in every non-local environment
SameSiteCookie sent on cross-site requests (CSRF)Lax, or Strict for admin apps
Path / DomainCookie sent to unrelated paths or subdomainsNarrowest that works
Max-AgeCookie kept after the browser closesUnset (session cookie)

4Session Fixation and changeSessionId()

Session fixation is an attack where the attacker does not steal the id but plants one. The attacker visits our site, gets a valid anonymous session id and tricks the victim into using it, for example through a link on an old server that still accepts URL rewriting. The victim logs in. If the application keeps the same id after login, the attacker's copy of the id is now an authenticated session.

The fix is simple: issue a new id at the moment of login. Since Servlet 3.1 we can call request.changeSessionId(), which keeps the session's attributes but gives it a fresh id and sends a new cookie. The old id the attacker holds now points to nothing. Spring Security does this for us by default through its session fixation protection, which uses changeSessionId.

Java
// After the password check succeeds:
String before = request.getSession().getId(); // A1B2...
request.changeSessionId();
String after = request.getSession().getId(); // 9F7E... (attributes kept)
session.setAttribute("user", user);

5Setting It Up in Spring Boot

In Spring Boot we set the cookie attributes through properties, and the embedded container applies them. Notice that tracking-modes=cookie turns off URL rewriting so the id never appears in a URL.

Properties
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=lax
server.servlet.session.tracking-modes=cookie
server.servlet.session.timeout=30m

With these in place, the Set-Cookie header looks like JSESSIONID=...; Path=/; Secure; HttpOnly; SameSite=Lax. It is worth checking the real header in the browser's developer tools after deployment, because a proxy or load balancer in front of the application can strip or rewrite cookie attributes.

6Follow-up questions

Where is session data stored by default, and why does that matter?

By default the container keeps sessions in its own memory. That is fast, but it means the session lives on one server only: if the server restarts, sessions are lost, and if a load balancer sends the next request to another server, the user looks logged out. That is why multi-instance deployments use sticky sessions or an external store such as Redis through Spring Session.

Is SameSite=Lax enough to stop CSRF?

It removes the most common attack, a hidden cross-site form post, but not every case. Requests from a sibling subdomain count as same-site, older browsers may ignore the attribute, and a GET that changes state is still exposed. So Lax is a strong extra layer, and CSRF tokens remain the main defence for state-changing requests.

Should we also invalidate the session on logout?

Yes. Logout should call session.invalidate() so the server forgets the session, and ideally clear the cookie as well. Deleting the cookie only in the browser is not enough, because anyone who copied the id could keep using it until the session timed out.

7Conclusion

In this answer, we saw that the container keeps session data on the server and identifies it with a random id carried in the JSESSIONID cookie. HttpOnly keeps scripts from reading that id, Secure keeps it on HTTPS, and SameSite limits cross-site sending to reduce CSRF. Finally, changing the id at login with changeSessionId() defeats session fixation, and Spring Boot exposes all of these settings as server.servlet.session properties.

What to say in the interviewAbout 80 seconds aloud

Open with

The container gives each user a random session id and keeps the actual session data on the server, in memory by default. The id goes to the browser in a cookie called JSESSIONID, and on every request the container reads that cookie and looks up the matching HttpSession.

Then, if they want more

Since the id is effectively the user's key, I protect the cookie. HttpOnly stops JavaScript from reading it, so an XSS bug cannot steal the session. Secure makes the browser send it only over HTTPS.

SameSite, usually Lax, stops the browser from attaching it to requests that come from other sites, which cuts down CSRF, although I still keep CSRF tokens for state-changing requests. I also turn off URL rewriting so the id never appears in links or logs.

The other important point is session fixation: if the id stays the same across login, an attacker who planted an id before login ends up with an authenticated session. So right after successful authentication I call request.changeSessionId(), which keeps the attributes but issues a new id; Spring Security does this by default.

In Spring Boot I set all of this with server.servlet.session.cookie properties and then check the real Set-Cookie header in the browser, because proxies sometimes change it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does the servlet container track a user session, and which cookie attributes should...": https://scrivio-interview-library.netlify.app/java/servlets/566c053d78/