Tomcat每次创建新HTTPRequest时,如何在多请求中维护同一Session对象?
HttpRequest Objects) Great question—this is a core part of how session management works in Tomcat, and it all boils down to tracking a unique session identifier across requests. Let me break down the process step by step:
Step 1: Session ID Creation on First Request
When a user sends their first request to a Tomcat-hosted servlet, Tomcat spins up a newHttpSessionobject and generates a unique, cryptographically randomJSESSIONID(this is the session's unique identifier). It immediately attaches this new session to the currentHttpRequest, so your servlet can access it viarequest.getSession().Step 2: Sending the Session ID to the Browser
Tomcat sends thisJSESSIONIDback to the user's browser using one of two standard methods:- HTTP Cookie (Default): Tomcat sets a cookie named
JSESSIONIDwith the session ID value. The browser stores this cookie and automatically includes it in every subsequent request to the same domain. - URL Rewriting (Fallback): If the browser has cookies disabled, Tomcat can rewrite URLs to append the session ID (e.g.,
http://yourapp.com/home;jsessionid=XYZ789...). This ensures session tracking still works, though it’s less common in modern apps.
- HTTP Cookie (Default): Tomcat sets a cookie named
Step 3: Linking Subsequent Requests to the Existing Session
For every newHttpRequestthat comes into Tomcat:- Tomcat first extracts the
JSESSIONID—either from the request’s cookies or from the rewritten URL. - It checks its internal session store (usually in-memory via
StandardManager, but configurable for persistent storage like databases) for aHttpSessionobject that matches this ID. - If a valid, non-expired session is found, Tomcat attaches that existing session to the new
HttpRequestobject. If no match exists (e.g., the session timed out or the ID is invalid), it creates a brand new session and correspondingJSESSIONID.
- Tomcat first extracts the
Behind the Scenes: The Session Manager
Tomcat’sManagercomponent is the workhorse here. It handles storing active sessions, managing session expiration (cleaning up old sessions automatically), and ensuring that each incoming request gets linked to the correct session using theJSESSIONIDas the key.
The key takeaway: The HttpRequest object is just a temporary container for the current request’s data, including a reference to the session. The actual HttpSession lives independently in Tomcat’s session store, so even though every request gets a new HttpRequest, they can all point to the same underlying session as long as they provide the right JSESSIONID.
内容的提问来源于stack exchange,提问作者Delphi

