-->

How do application servers keep track of HttpSessi

2019-08-01 15:14发布

问题:

How do application servers keep track of which client is associated with which HttpSession object? Is it related to keeping track of the TCP/IP connection between the client? Or cookies perhaps? I doubt it's cookies since there is a separate method for extracting cookies.

Background

I understand that servlets and JSPs can call request.getSession() to obtain an HttpSession object associated with a client. I'm curious as to how the server knows to return that same object when the client requests new pages. I've searched around and all documentation I find is on how to extract session information. I'm interested in how the server isolated that session information from the sea of client data it has access to.

回答1:

I doubt it's cookies

It is! There are essentially two ways of keeping track of user session in stateless HTTP protocol and servlets: JSESSIONID cookie or URL rewriting. The latter is used when cookies are not available.

With first response servlet container sets the following cookie in the client:

Set-Cookie: JSESSIONID=25E7A6C27095CA1F560BCB2983BED17C; Path=/; HttpOnly

Every subsequent request includes this cookie, and servlet container uses it to provide correct HttpSession. You can access this cookie directly using servlet API, you can even build your own session mechanism on top of JSESSIONID or some other cookie. But the servlet container does that for you.

See also

  • Why is jsessionid appearing in Wicket URLs when cookies are enabled? - for some technical details on how servlet container makes a distinction between cookies and URL rewriting