• When a client visits the webapp for the first time, and HttpSession is obtained for the first time the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and store it in the server’s memory.
  • The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.
  • As per the HTTP cookie specification the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid.
  • The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server’s memory.
  • The HttpSession stays alive until it has not been used for more than the timeout value specified in <session-timeout>, a setting in web.xml. The timeout value defaults to 30 minutes.
  • So, when the client doesn’t visit the web app for longer than the time specified, the servlet container trashes the session.
  • Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.
  • On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client’s side.
  • In a new browser instance, the cookie associated with the session wouldn’t exist, so it would no longer be sent.
  • This causes an entirely new HTTPSession to be created, with an entirely new session cookie begin used.
// get or create new session if doesn't exist
HttpSession session = request.getSession(); 

// add some value to session object
session.setAttribute("user", name);   

// read values from session object
session.getAttribute("user"); 

//  sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file
response.sendRedirect("Welcome");  

 // always create a new session object
HttpSession session = request.getSession(true);

// destroy the session, mainly used at time of Logout call
session.invalidate(); 

// returns a string containing the unique identifier assigned to the session.
session.getId();  
Lifecycle of HttpSession
  • The HttpSession lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn’t timed out at the server side.
  • It is shared among allrequests in the same session.
Categories: JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.