Http Session Management – Cookie

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

http cookie theory

Cookie Attributes

It has 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 that stored in it.
  3. Domain:
    Which domain it belong 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 maximize seconds that it will live. After that time it will be deleted.

Cookie Types

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

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

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 user do not know where it saved at.

Cookie Disadvantage

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

How to create cookie in java servlet

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

  1. Cookie(String name, String value): Create a new object with 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’s belong url path.
  12. void setSecure(boolean flag): When set to true means browser only send it back to server when use HTTPS or SSL secure protocol, false is the opposite case.
READ :   ServletConfig Vs ServletContext

How to add cookie to client browser

HttpServletResponse.addCookie() method can be used to add it to client

Cookie ckUserName = new Cookie("userName", userName);
resp.addCookie(ckUserName);

How to get cookie from client browser 

HttpServletRequest.getCookies() method can get all cookies that belong to this www domain and path. It return 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();
					}
				}
			}

How to delete cookie in client browser

  1. setMaxAge(0) is used to delete it.
    You can use this method to invalidate a user status for example when user log out of website or empty shopping cart.
  2. setMaxAge(-1) means it will be a none persistent type, which will be removed when browser closed.
  3. setMaxAge(10000) : If add this cookie to client, it will persist until after 10000 seconds, so you can read it out in java code during that time when client access 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);

Example

This is just a user register example that use cookie to implement. There has three jsp pages and one servlet.

  1. http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserAccount.jsp
    Let user input user name and password.
  2. http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserEmail.jsp
    Let user input user email.
  3. http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieFinishRegister.jsp
    Let user to confirm the input data.
  4. com.dev2qa.example.servletsession.SessionManageCookie
    This is the servlet that control all register process. Include create, set and read cookie from client etc.
READ :   Spring MVC Request And Session Scoped Bean Example

Source Codes

  1. /pages/regist/cookieInputUserAccount.jsp

    Access Url: http://localhost:8080/Dev2qaWebAppExample/pages/regist/cookieInputUserAccount.jsp
    cookieInputUserAccount jsp page

    <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
    cookieInputUserEmail jsp page

    <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
    cookieFinishRegister jsp page

    <%
    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
    com.dev2qa.example.servletsession.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);
    		}
    	}

     

Download “Http-Session-Management-Cookie-Example-Code.zip” Http-Session-Management-Cookie-Example-Code.zip – Downloaded 79 times – 54 KB

(Visited 213 times, 1 visits today)

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.