Http Session Management – Cookie

A cookie is a small piece of data stored in a web browser’s cache or text file in a user machine by a web server. It can be sent back to the web server again when the client user uses the same web browser to access the same web server at next time. Then web server can use stored data in it to distinguish different client users. In one word, You can think cookie as a data capsule shared among multiple client requests to the same web server. So cookies can be used to implement HTTP session. You can save data in it when the session starts and make it invalidate when the session stopped.

1. Cookie Attributes.

Cookie has the following attributes:

  1. Name: This is a must-have attribute. The name should be unique under it’s belonged domain.
  2. Value: This is the data value stored in it.
  3. Domain: Which domain it belongs to. It is only available for the request to this domain. Such as www.dev2qa.com
  4. Path: This is the path under the domain. For example, if the path value is /subfolder1 then it will be available to all the pages or folders under www.dev2qa.com/subfolder1.
  5. Max Age: The maximum seconds that it will live. After that time it will be deleted.

2. Cookie Types.

Since it can be saved in a web browser cache or a text file on user’s machine. So it is divided into two types.

  1. Non-Persistent: This is only available in a single session, when the user closes the web browser, it is removed from the browser cache also.
  2. Persistent: Is available for multiple sessions, it will not be removed when the user closes the web browser, only can be removed by java code in the servlet.

3. Cookie Advantage.

  1. Operate at server side(create, remove, etc), saved at client side.
  2. Simplify data transfer than hidden form field. Make java code simple and clear.
  3. More secure. You can save encrypted data in it, and client users do not know where it saved.

4. Cookie Disadvantage.

  1. Can only store textual data.
  2. If the web browser disables it then it can not work.

5. How to create cookies in java servlet.

You can use class javax.servlet.http.Cookie to create a cookie and set it’s attribute. This class provides the following methods:

  1. Cookie(String name, String value): Create a new cookie object with a specified name and value.
  2. void setName(String name): Set it’s name value to the specified name.
  3. String getName(): Return it’s name.
  4. void setValue(String value): Set it’s value.
  5. String getValue(): Return it’s value.
  6. void setMaxAge(int expiry): Set it’s maximum age in seconds.
  7. int getMaxAge(): Return it’s max age in seconds.
  8. void setDomain(String domain): Set it’s belong domain.
  9. String getDomain(): Get it’s belong domain.
  10. void setPath(String path): Specify it’s belong url path under it’s domain.
  11. String getPath(): Return it belongs url path.
  12. void setSecure(boolean flag): When set to true means the browser only send it back to the server when use HTTPS or SSL secure protocol, false is the opposite case.

6. How to add a cookie to the client browser.

  1. HttpServletResponse.addCookie() method can be used to add a cookie to client.
    Cookie ckUserName = new Cookie("userName", userName);
    resp.addCookie(ckUserName);

7. How to get a cookie from the client browser.

  1. HttpServletRequest.getCookies() method can get all cookies that belong to this www domain and path. It returns an array of cookie object.
    String userName = "";
    String password = "";
    String email = "";
    		
    /* Get below data from client. */
    Cookie[] ckArr = req.getCookies();
    if(ckArr!=null)
    {
    	int len = ckArr.length;
    	for(int i=0;i<len;i++)
    	{
    		Cookie ckTmp = ckArr[i];
    		if("userName".equalsIgnoreCase(ckTmp.getName()))
    		{
    			userName = ckTmp.getValue();
    		}else if("password".equalsIgnoreCase(ckTmp.getName()))
    		{
    			password = ckTmp.getValue();
    		}if("email".equalsIgnoreCase(ckTmp.getName()))
    		{
    			email = ckTmp.getValue();
    		}
    	}
    }

8. How to delete cookies in a client browser.

  1. setMaxAge(0) is used to delete a cookie. You can use this method to invalidate a user status for example when a user logs out of a website or empty a shopping cart.
  2. setMaxAge(-1) means it will be a none persistent type, which will be removed when the browser closed.
  3. setMaxAge(10000): If add this cookie to the client, it will persist until after 10000 seconds, so you can read it out in java code during that time when the client access the website again.
    Cookie ckUserName = new Cookie("userName", userName);
    
    /* If uncomment below code, ckUserName will be deleted in next page.*/
    //ckUserName.setMaxAge(0);
    			
    Cookie ckPassword = new Cookie("password", password);
    
    /* If uncomment below code, ckPassword will be deleted when the browser close.*/
    //ckPassword.setMaxAge(-1);
    
    Cookie ckEmail = new Cookie("email", email);
    
    /* ckEmail will save to client machine text file for about 10000 seconds.*/
    ckEmail.setMaxAge(10000);

9. Cookie Example.

This is just a user register example that uses a cookie to implement. There are three JSP pages and one servlet.

  1. http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserAccount.jsp, this JSP page let user input user name and password.
  2. http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserEmail.jsp, this JSP page let user input user email.
  3. http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieFinishRegister.jsp, this JSP page lets users confirm the input data.
  4. com.dev2qa.example.servletsession.SessionManageCookie, this is the servlet that controls all registration process. Include create, set and read cookies from clients.

9.1 Source Codes.

  1. /pages/regist/cookieInputUserAccount.jsp, Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserAccount.jsp
    <form action="/Dev2qaWebAppExample/SessionManageCookie" 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/cookieInputUserEmail.jsp, Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserEmail.jsp
    <form action="/Dev2qaWebAppExample/SessionManageCookie" 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/cookieFinishRegister.jsp, Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieFinishRegister.jsp
    <%
    String userName = "";
    String password = "";
    String email = "";
    /*Get below data from client.*/
    Cookie[] ckArr = request.getCookies();
    if(ckArr!=null)
    {
    	int len = ckArr.length;
    	for(int i=0;i<len;i++)
    	{
    		Cookie ckTmp = ckArr[i];
    		if("userName".equalsIgnoreCase(ckTmp.getName()))
    		{
    			userName = ckTmp.getValue();
    		}else if("password".equalsIgnoreCase(ckTmp.getName()))
    		{
    			password = ckTmp.getValue();
    		}if("email".equalsIgnoreCase(ckTmp.getName()))
    		{
    			email = ckTmp.getValue();
    		}
    	}
    }
    %>
    <form action="/Dev2qaWebAppExample/SessionManageCookie" method="post">
    <input type="hidden" name="action" value="finishRegister" />
    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>
  4. com.dev2qa.example.servletsession.SessionManageCookie, Access Url: http://localhost:8080/Dev2qaWebAppExample/SessionManageCookie.
    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");
    			
    		Cookie ckUserName = new Cookie("userName", userName);
    		
    		/* If uncomment below code, ckUserName will be deleted in next page.*/
    		//ckUserName.setMaxAge(0);
    			
    		Cookie ckPassword = new Cookie("password", password);
    		
    		/* If uncomment below code, ckPassword will be deleted when the browser close.*/
    		//ckPassword.setMaxAge(-1);
    		
    		resp.addCookie(ckUserName);
    		resp.addCookie(ckPassword);
    			
    		targetUrl = "/pages/regist/cookieInputUserEmail.jsp";
    	}else if("inputUserEmail".equalsIgnoreCase(action))
    	{			
    		/* Get email from user input text box. */
    		String email = req.getParameter("email");
    			
    		Cookie ckEmail = new Cookie("email", email);
    			
    		/* ckEmail will save to client machine text file for about 10000 seconds.*/
    		ckEmail.setMaxAge(10000);
    		
    		resp.addCookie(ckEmail);
    			
    		targetUrl = "/pages/regist/cookieFinishRegister.jsp";
    	}else if("finishRegister".equalsIgnoreCase(action))
    	{
    		String userName = "";
    		String password = "";
    		String email = "";
    		
    		/* Get below data from client. */
    		Cookie[] ckArr = req.getCookies();
    		if(ckArr!=null)
    		{
    			int len = ckArr.length;
    			for(int i=0;i<len;i++)
    			{
    				Cookie ckTmp = ckArr[i];
    				if("userName".equalsIgnoreCase(ckTmp.getName()))
    				{
    					userName = ckTmp.getValue();
    				}else if("password".equalsIgnoreCase(ckTmp.getName()))
    				{
    					password = ckTmp.getValue();
    				}if("email".equalsIgnoreCase(ckTmp.getName()))
    				{
    					email = ckTmp.getValue();
    				}
    			}
    		}
    			
    		PrintWriter pw = resp.getWriter();
    		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
    	{
    		/* No action request parameter then go to first page of register*/
    		targetUrl = "/pages/regist/cookieInputUserAccount.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);
    	}
    }

Leave a Comment

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.