Reputation: 1661
What is the difference between request.getSession().getId()
and request.getRequestedSessionId()
? Do both of them return the same thing i.e. Session Id?
Thanks
Upvotes: 6
Views: 16708
Reputation: 27450
HttpRequest.getRequestedSessionId()
is the session id provided by the caller, usually with the JESSIONID cookie whereas HttpRequest.getSession().getId()
is the id effectively used by the server.
For an ongoing session, the JESSIONID cookie, or the value of HttpRequest.getRequestedSessionId()
allows the server to find the ongoing session by id.
For new sessions, you might be very tempted to set the servers session id by supplying a value via the JESSIONID cookie, i.e. the value of HttpRequest.getRequestedSessionId()
. This would make it easy to correlate a chain of calls to multiple servers initiated by an initial call from the customer's browser. However, the semantics of HttpRequest.getRequestedSessionId() does not allow such chaining.
Indeed, the JESSIONID cookie has an effect only for a session already existing in the server and which was previously sent to the client. If the JESSIONID cookie refers to a nonexistent session id, the server creates a new session ignoring the value of JESSIONID cookie.
You can convince yourself of the above, by reading the source code of the doGetSession(boolean)
in the org.apache.catalina.connector.Request
class.
Upvotes: 3
Reputation: 5715
request.getRequestedSessionId()
will return the session id specified by the client (presumably in a cookie). request.getSession().getId()
will return the server's session id (if a session does not exist, request.getSession()
will create it).
The important difference is that you can't rely on the value returned by request.getRequestedSessionId()
, since it may not be valid. From the documentation:
Returns the session ID specified by the client. This may not be the same as the ID of the current valid session for this request. If the client did not specify a session ID, this method returns null.
Upvotes: 18