Http Session Management – HttpSession

HttpSession is used to save user session-related information. It is provided by java servlet API. When a session request comes to a servlet container, it will create a HttpSession object on the server-side and then assign a unique id to the session object. The session id will be returned back to the client browser, and it will be saved either by cookie or request url parameter. So when the client requests to web server again, it will send the session id back to the web server also. Then web server will know who the client is by the session id and its stored value.

1. HttpServletRequest interface’s methods to obtain HttpSession object.

  1. public HttpSession getSession(): Returns the existing HttpSession object related to this request. If the value is null then create and return a new one.
  2. public HttpSession getSession(boolean create): Returns the existing HttpSession object related to this request. If the value is null and the input parameter “create” is true then create a new session object to return.

2. Other important methods.

  1. Object getAttribute(String name): Returns the saved object in this HttpSession object with the specified object name, or null if there is no object found with the name. HttpSession’s other methods to manage attributes are setAttribute(String name, Object value), removeAttribute(String name) and getAttributeNames().
  2. String getId(): Returns a unique identifier string assigned to current HttpSession object. This is also called JSESSIONID, it will be saved at client cookie or request URL.
  3. ServletContext getServletContext():  Returns the web applicaion’s ServletContext object. This is an application scope object. You can save information in it when you want to use the stored data throughout the whole web application.
  4. long getCreationTime(): Returns current HttpSession create time in milliseconds from January 1, 1970 GMT.
  5. long getLastAccessedTime(): Return the last access time of current HttpSession object.
  6. getMaxInactiveInterval(): Get the max inactive seconds between two request in the same HttpSession.
  7. setMaxInactiveInterval(int interval): Set the max inactive seconds between two requests in the same session. If timeout then the session will be removed by the servlet container.
  8. void invalidate(): Make the session invalidate and remove all its stored objects.

3. JSESSIONID.

  1. JSESSIONID is the unique identifier related to the current HttpSession. It is created by servlet container when you use HttpServletRequest.getSession() method to create a session object.
  2. The JSESSIONID‘s value is sent back and saved to the client by cookie. If client-side disable cookie then we use url rewriting to save it’s value in the request url parameter.

4. Sessions and Clusters.

  1. If you have a cluster with two or more web servers, remember that one server saved session object values is probably not available in the other server. So, in the case when the cluster divides a client’s requests between two or more servers, occasionally session values might be lost.

4.1 The solution for this issue.

  1. Use a database to store session attributes values. Then all servers in the cluster can read, write the same data from the database.
  2. Use a session server, all the session-related data and events will be sent to this server to verify and manage. It is something like a database but it is faster than DB because all the operations will be handled in memory.

5. HttpSession Advantage.

  1. Secure. All data will operate on the server-side.
  2. Make java code simple and clear.
  3. Can store session object values data in file or DB.
  4. When used in the cluster, a session server can be used to manipulate session issues for requests from all the servers in the cluster.
  5. Do not rely on cookie, can still work if client disables cookie.

6. HttpSession Example.

This is a user registration system implemented with HttpSession.

  1. http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserAccount.jsp, Allow user to enter user name and password.
  2. http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserEmail.jsp, Allow user to enter email.
  3. http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionFinishRegister.jsp, User confirm entered information on this page.
  4. com.dev2qa.example.servletsession.SessionManageHttpSession, The servlet for logic verification and page navigation.

6.1 Example Source Codes.

  1. /pages/regist/httpSessionInputUserAccount.jsp, Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserAccount.jsp
    <form action="/Dev2qaWebAppExample/SessionManageHttpSession" method="post">
    <input type="hidden" name="action" value="inputUserAccount" />
    UserName: <input type="text" id="userName" name="userName"/><br/>
    Password: <input type="password" id="password" name="password"/><br/>
    <input type="submit" value="Submit"/>
    </form>
  2. /pages/regist/httpSessionInputUserEmail.jsp, Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionInputUserEmail.jsp
    <form action="/Dev2qaWebAppExample/SessionManageHttpSession" method="post">
    <input type="hidden" name="action" value="inputUserEmail" />
    Email: <input type="text" id="email" name="email"/><br/>
    <input type="submit" value="Submit"/>
    </form>
  3. /pages/regist/httpSessionFinishRegister.jsp, User confirm page, Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/httpSessionFinishRegister.jsp, if user click “Invalidate This Session” link on the finish register page then it will invalidate the HttpSession.
    <%
    String userName = "";
    String password = "";
    String email = "";
    /* Get below data from HttpSession. */
    HttpSession reqSession = request.getSession();
    
    String JSESSIONID = reqSession.getId();
    
    Object userNameObj = reqSession.getAttribute("userName");
    Object passwordObj = reqSession.getAttribute("password");
    Object emailObj = reqSession.getAttribute("email");
    
    /*Get the message object form HttpServletRequest. */
    String message = request.getParameter("message");
    if(message==null)
    {
    	message = "";
    }
    
    if(userNameObj!=null)
    {
    	userName = (String)userNameObj;
    }
    
    if(passwordObj!=null)
    {
    	password = (String)passwordObj;
    }
    
    if(emailObj!=null)
    {
    	email = (String)emailObj;
    }
    
    %>
    <form action="/Dev2qaWebAppExample/SessionManageHttpSession" method="post">
    <input type="hidden" name="action" value="finishRegister" />
    <%=message %><br/><br/>
    JSESSIONID: <%=JSESSIONID %><br/><br/>
    Please confirm below user information then click Finish button to register.<br/><br/>
    User Name: <%=userName %><br/>
    Password: <%=password %><br/>
    Email: <%=email %><br/>
    <input type="submit" value="Finish"/>
    </form>
    
    Click <a href="/Dev2qaWebAppExample/SessionManageHttpSession?action=invalidateSession">Invalidate This Session</a> to invalidate and remove all the stoerd data value in it.
    
  4. com.dev2qa.example.servletsession.SessionManageHttpSession
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	/* Use action value to check current step page.*/
    	String action = req.getParameter("action");
    		
    	boolean needForward = true;
    	String targetUrl = "";
    	if("inputUserAccount".equalsIgnoreCase(action))
    	{
    		/* Get below data from user input text box.*/
    		String userName = req.getParameter("userName");
    		String password = req.getParameter("password");
    			
    		HttpSession reqSession = req.getSession(true);
    		reqSession.setAttribute("userName", userName);
    		reqSession.setAttribute("password", password);
    		
    		targetUrl = "/pages/regist/httpSessionInputUserEmail.jsp";
    	}else if("inputUserEmail".equalsIgnoreCase(action))
    	{			
    		/* Get email from user input text box. */
    		String email = req.getParameter("email");
    			
    		HttpSession reqSession = req.getSession(true);
    		reqSession.setAttribute("email", email);
    			
    		targetUrl = "/pages/regist/httpSessionFinishRegister.jsp";
    	}else if("finishRegister".equalsIgnoreCase(action))
    	{
    		String JSESSIONID = "";
    		String userName = "";
    		String password = "";
    		String email = "";
    		
    		HttpSession reqSession = req.getSession(true);
    		
    		JSESSIONID = reqSession.getId();
    			
    		Object userNameObj = reqSession.getAttribute("userName");
    		Object passwordObj = reqSession.getAttribute("password");
    		Object emailObj = reqSession.getAttribute("email");
    			
    		if(userNameObj!=null)
    		{
    			userName = (String)userNameObj;
    		}
    			
    		if(passwordObj!=null)
    		{
    			password = (String)passwordObj;
    		}
    			
    		if(emailObj!=null)
    		{
    			email = (String)emailObj;
    		}
    			
    		PrintWriter pw = resp.getWriter();
    		pw.println("JSESSIONID : " + JSESSIONID);
    		pw.println("User Name : " + userName);
    		pw.println("Password : " + password);
    		pw.println("Email : " + email);
    		pw.println("Your user information has been registered successful.");
    		needForward = false;
    	}else if("invalidateSession".equals(action))
    	{
    		HttpSession reqSession = req.getSession(true);
    		String JSESSIONID = reqSession.getId();
    			
    		reqSession.invalidate();
    			
    		String errMessage = "Session has been invalidate, JSESSION id is " + JSESSIONID + ", the value stored in this session had been removed.";
    		
    		/* Save the error message in request url parameter. Because reqSession has been invalidate, if call it again there will throws an exception.*/
    		targetUrl = "/pages/regist/httpSessionFinishRegister.jsp?message="+errMessage;
    	}else
    	{
    		/* No action request parameter then go to first page of register*/
    		targetUrl = "/pages/regist/httpSessionInputUserAccount.jsp";
    	}
    		
    	if(needForward)
    	{
    		/* 
    	     We need to get the web application context path as the root path of each next page url.
    		 * */
    		String contextPath = this.getServletContext().getContextPath();
    		resp.sendRedirect(contextPath + targetUrl);
    	}
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x