First of all, it is important to note that a servlet container does not necessarily create a new instance of HttpServletRequest
for each request.
Tomcat, for example, recycles existing instances of HttpServletRequest
as a performance optimization to reduce heap allocation. After a response has been committed, it resets the internal state of the existing HttpServletRequest
instance and reuses that same instance for the next request. Same thing for the HttpServletResponse
instance.
As a consequence, since this object is not immutable it's critically important to make sure that a HttpServletRequest
object is not referenced anywhere outside the lifecycle of a single request.
To answer the OP's question: the HttpSession
object is not something that's stored in a field of HttpServletRequest
. HttpServletRequest.getSession()
is just an API method, and the servlet engine typically implements it by retrieving the HttpSession
from the session storage mechanism using the session ID provided by the request.
- NOTE: there is also no guarantee that that the same actual instance of
HttpSession
will be returned for subsequent requests connected to the same session (see this question)