Search This Blog

Wednesday, April 17, 2013

Servlet Session Tracking with cookies (JSESSIONID)

A quick recap on how session tracking works with cookies:

A) first request from client
  • New session is created only if HttpServletRequest.getSession is called
  • Session id (JSESSIONID) is generated 
  • Response contains JSESSIONID cookie
    (e.g. Set-Cookie: JSESSIONID=762F504BFD0E69A5A8C8F9B53DDD42BB)
[TOMCAT] The Request.doGetSession creates session using StandardManager and then sets the JSESSIONID to a random number generated by ManagerBase.generateSessionId. The cookie itself is added to the response using Response.addSessionCookieInternal.

B) subsequent requests from client

  • HttpServletRequest.getSession returns the session for the client based on the value of the JSESSIONID cookie
  • HttpServletRequest.isRequestedSessionIdFromCookie returns true
  • Response may but typically does not contain JSESSIONID cookie anymore as it was sent in the 1st response

[TOMCAT] CoyoteAdapter.service uses CoyoteAdapter.parseSessionCookiesId to get the value of the JSESSIONID cookie and then binds the session id to the request using Request.setRequestedSessionId so that Request.doGetSession can find the session later using StandardManager.findSession.