state management using cookie

In this post, you will learn:

  • How to maintain user state between requests using cookies?
  • How to create Cookie objects?
  • How to send and receive Cookie objects in servlets?

In the last post we have understood the need of state management and the concept of cookies. In this post we will cover a practical example of state management using cookie in a web application. For this we need to learn how cookies are represented and managed in Java.

Object representation of cookies

In a Java web application, a cookie is represented as an object. javax.servlet.http.Cookie class is provided by Servlet API to represent and manage cookies as objects.

A Cookie object is created using the following constructor.

public Cookie(String name,String value);

Commonly used methods of the Cookie class:

1. getName(): This method is used to obtain the name of a cookie.

public String getName();

2. getValue(): This method is used to obtain the value of a cookie.

public String getValue();

3. setMaxAge(): This method is used to set the validity time of a cookie. When validity is associated to a cookie, it becomes persistent.

public void setMaxAge(int timeInSeconds);

4. getMaxAge(): This method is used to obtain the validity time of a cookie.

public int getMaxAge();

Methods to send and receive cookies:

addCookie() method of HttpServletResponse interface is used to add the cookies to the response i.e. to send them to the client.

public void addCookie(Cookie ck);

getCookies() method of HttpServletRequest interface is used to obtain the cookies which are received as part of the request. When no cookie is received, null is returned by the method.

public Cookie[] getCookies();

To test the cookies practically, we are creating an application which have two servlets by the name WelcomeServlet and TourServlet. A user initially sends a request to the WelcomeServlet and provides his name as input. Using the response page of the WelcomeServlet, the user sends another request to the TourServlet. The TourServlet needs the user name to generate a personalized message for the user. The user name is made available to it with the help of a cookie. From the WelcomeServlet a cookie containing the user name is sent as part of the response. This cookie is made available to the TourServlet in the next request. Following diagram describes the page flow of the web application.

cookie_app_page_flow

Practical example of state management using cookie:

First, the index.html :

<form method="post" action="welcomeServlet">
Name <input type="text" name="name"> <br/>
<input type="submit" value="submit">
</form>

Second the WelcomeServlet. It sends a cookie containing the user name as part of the response so that the user name can be made available to the TourServlet in the next request.

package com.techmentro.learningpad;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet 
{
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		//Value of name request parameter is read
		String user=request.getParameter("name");
		//A cookie object is created to store the user name
		Cookie ck=new Cookie("userName",user);
		//expiration time is set for the cookie
		ck.setMaxAge(600);
		//cookie is added to the response
		response.addCookie(ck);
		
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.println("Welcome, "+user);
		//A hyper link  is added to send the request to the tourServlet
		out.println("<br> Take a Tour");
		out.close();
	}
}

Third, the TourServlet. It receives the cookie which was sent by the WelcomeServlet.

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class TourServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		//user name is set to Guest, so that it can be displayed when no cookie is received.
		String user="Guest";
		//Cookies which may have been sent by the browser are read
		Cookie ck[]=request.getCookies();
		//If the array isn't null i.e. some cookies are received
		if(ck!=null)
		{
			//value of the first cookie is read because we sent only one cookie in the last request
			user=ck[0].getValue();
			
		}
		
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		//Guest or user name obtained from the cookie is displayed.
		out.println("Sorry, "+user);
		out.println("<br> Site is down for routine maintenance. Visit again later.");
		out.close();
	}
}

Fourth, the web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
 <servlet-name>s1</servlet-name>
 <servlet-class>com.techmentro.learningpad.WelcomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>s1</servlet-name>
 <url-pattern>/welcomeServlet</url-pattern>
 </servlet-mapping>
 <servlet>
 <servlet-name>s2</servlet-name>
 <servlet-class>com.techmentro.learningpad.TourServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>s2</servlet-name>
 <url-pattern>/tourServlet</url-pattern>
 </servlet-mapping> 
</web-app>

Output screen images of the practical example:

The first screen represents the home page generated by index.html. Two different browsers are used to represent two different users.

cookie_screen1

The second screen represents the response of the WelcomeServlet. The response page contains the welcome message for the user and a link to send the request to the TourServlet.

cookie_screen2

The third screen represents the response of the TourServlet. The user name displayed in this response page is obtained from the cookie.

cookie_screen3

The fourth screen also represents the response of the TourServlet. To generate this response, clear all the cookies from the browser and directly send a request to the TourServlet bypassing the WelcomeServlet. In such a case, no cookie will be received by the TourServlet hence it will generate the generalized sorry message.

cookie_screen4

Its time to recap the main concepts:

  1. javax.servlet.http.Cookie class is used to represents cookies as object in a Java web applcation.
  2. addCookie() method of HttpServletResponse interface is used to send cookie as part of the response.
  3. getCookies() method of HttpServletRequest interface is used to obtain the received cookies in a servlet.
  4. setMaxAge() method of Cookie class is used to make a cookie persistent.
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

5 thoughts on “state management using cookie

  1. Dear Sir,
    Thank you very much for this describing the topic in such an easy and understandable format.
    One thing that I would like to ask here is;
    while using Cookie ck[]=request.getCookies();
    is it necessary the cookie that is recieved here will always occupy the very first position(0th index) of array? can it be other than first position??

    1. Actually, In this example, we have sent only one cookie to the client hence only one cookie will be received back which will be the first one. If multiple cookies are sent then multiple will be received back and their order may not be same as sent. They need to be identified by their name.

  2. Dear Sir,
    Thank you very much for describing the topic in such an easy and understandable format.
    One thing that I would like to ask here is;
    while using Cookie ck[]=request.getCookies();
    is it necessary the cookie that is recieved here will always occupy the very first position(0th index) of array? can it be other than first position??

  3. Dear Sir,
    Thank you very much for describing the topic in such an easy and understandable format!..
    one thing that I would like to ask here is;
    while using Cookie ck[]=request.getCookies();
    Is it necessary that cookie received will always occupy the very first position(0th index) of array? can be other than first location??

Leave a Reply

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