Search code examples
jspsessionservletssession-cookiesjsessionid

right way to add session in java servlet


I am new in this area. I was wondering if only calling "request.getSession(true)" in java servlet is enough to start session tracking. What about adding JsessionID in cookie c, setting path for c and response.addCookie(c) steps before redirecting response to next jsp.


Solution

  • Servlet container will do all of this for you. Just call getSession(true) and the JSESSIONID cookie is added to the next response (providing that response headers were not yet sent). Actually, servlet container tries to abstract you from implementation details and just provides HTTP session abstraction.

    Also by default every JSP file creates session once accessed. Extra care must be taken when server does not support cookies, URL-rewriting must be taken into account when rendering URLs.

    See also