Servlet Cookies Simple Shopping Cart Example

April 5, 2014 | Servlets

Note: You can see the JESSIONID (Session ID) in the output screens at the end.

Note: For better understanding, the subject is discussed in Question/Answer format.

Note: Before going into this example, it is advised to go through the Cookie API methods and their explanation because these methods are used in this example.

1. What is Cookie?

For us, Cookie is a class from javax.servlet.http package. But in the open world, a Cookie represents a sweet Biscuit or Chocolate.

2. What a Cookie can store?

Cookie stores small strings of data. Cookies stay all through the session. Programmer can store the session data with Cookie object. It is another style of tracking session data (the first way is using HttpSession interface).

3. Who creates Cookies and where they are stored?

Servlet Cookies are created on the server (by Servlet container) and sent to the client's browser for temporary storage. The Servlet Cookies can be sent to and fro between client and server in their conversation. Client is not aware of the entire process of Cookie management as everything is done by the server and client is kept completely transparent.

4. What Cookie can do in Servlets?

Servlet Cookies are used mainly for tracking different types of client's information. That is, the Web server can store data on the client browser in the form of Cookie objects.

Typical uses of a Cookie are

  1. To store User name and Password
  2. To write Shopping cart in e-Commerce application
  3. Advertisement on client browser
  4. Customization of Web sites etc.

5. How Servlet Cookies stored on the client are recognized by the server later? The Cookie object created on the server is attached to response object and sent to client. The Cookie carries implicitly (as response header) the server information like name, path, host and connection type etc. and the combination of this information is used by server to know cookie is coming from which client.

6. All Cookies are same or any types exist?

Yes, there are two types of cookies and they are differentiated on their life span.

  1. Session Cookies: Session cookies get expired and deleted from browser when the browser closes, thereby, they do not carry any expiration time constraint parameter. They are stored temporarily (just for the usage of session) in the RAM memory.
  2. Persistent Cookies: As the name indicates, they persist long time on the client browser. The time of expiration can be set programmatically for each Cookie. These Cookies are stored on hard disk. The Cookie gets deleted automatically when the time or age expires.

With this knowledge of Cookies, let us go for an example. In this code, we create a cookie in the Servlet, sent to client to store on the browser, later retrieved from client and information available with the cookie is printed.

The entire program moves around a Shopping cart, an important module of e-Commerce application. While going to a Shopping Mall, nearby to our house, physically we take a wheel cart to place the items we would like to buy. But as our program represents an online Mall, here shopping cart is imaginary but have all the operations you do on a physical cart like adding items, deleting, replacing, searching etc. For simplicity, only I took two operations only of Adding items and Searching (or Listing) items and these operations are performed through Servlet Cookies.

Example on Servlet Cookies

As usual there exist two programs of Client HTML and server Servlet.

HTML File: ShoppingCart.html

<h3>Cookie Example through Shopping Cart</h3>

<form method="get" action="http://localhost:8888/india/SC">
  
  Enter Item Name <input type="text" name="item"><br>
  Enter Item Quantity <input type="text" name="qty"><br>
  <input type="submit" value="Add Cookie" name="add">
  <input type="submit" value="List Cookies" name="list">

</form>

Observe, fist time we are having two submit buttons in a single

tag. Click any submit button, the same servlet is called. Then how to differentiate the submit button clicked by the user and accordingly action taken by the Programmer on Servlet? Observe, the names of two submit buttons are add and list. We see this in Servlet program.

web.xml entry for ShoppingCart servlet

<servlet>
  <servlet-name>snrao1</servlet-name>
  <servlet-class>ShoppingCart</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>snrao1</servlet-name>
  <url-pattern>/SC</url-pattern>
</servlet-mapping>

Servlet File: ShoppingCart.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCart extends HttpServlet    
{
  public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException   
  {
    String str1 = req.getParameter("item");       // item name
    String str2 = req.getParameter("qty");        // item quantity
    String str3 = req.getParameter("add");        // submit button by name add
    String str4 = req.getParameter("list");       // submit button by name list

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
						
    if(str3 != null)    
    {    
      Cookie c1 = new Cookie(str1, str2);                                
      res.addCookie(c1);                                                        
      res.sendRedirect("ShoppingCart.html"); 
    }			                                                         
    else if(str4 != null)  
    { 
      Cookie clientCookies[] = req.getCookies();       
      for( int i = 0; i &lt; clientCookies.length; i++)     
      {
        out.print("<b>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue() + "</b><br>");
      }                
    }
    out.close( ) ;
  }        
} 

Let us discuss the code linewise.

  String str1 = req.getParameter("item");     // item name
  String str2 = req.getParameter("qty");      // item quantity
  String str3 = req.getParameter("add");      // submit button by name "add"
  String str4 = req.getParameter("list");     // submit button by name "list"

With the first two statements you are well aware of. Observe the last two statements are for submit buttons. When user clicks add submit button, the str3 contains value Add Cookie and str4 contains null. Similarly, when user clicks list submit button, the str4 contains the value List Cookies and str3 contains null. With null values of strings str3 and str4, the Programmer can differentiate from which submit button the Servlet is invoked.

						
if(str3 != null)    
{    
  Cookie c1 = new Cookie(str1, str2);      // create a Cookie object                             
  res.addCookie(c1);                       // send cookie object to client 
  res.sendRedirect("ShoppingCart.html");   // send a fresh form to client
}	

When str3 is not equal to null? It is obviously when user clicks add submit button. That is, above if condition is executed when user clicked add submit button. A Cookie object c1 is created and its constructor is passed with two string parameters str1 (item name) and str2 (item quantity). We know earlier, the Cookie stores small strings of data. Later the Cookie object c1 is sent to client by calling the method addCookie() of HttpServletResponse interface. To make the code user friendly, a fresh static HTML form is sent to client with sendRedirect() method for filling next item and quantity.

Note: As server is sending the HTML form, copy the ShoppingCar.html to the base folder india.

		                                                         
else if(str4 != null)  
{ 
  Cookie clientCookies[] = req.getCookies();      // retrieve cookies from client    
  for( int i = 0; i &lt; clientCookies.length; i++)     
  {                                               // print item name and item quantity of each cookie
    out.print("<b>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue() + "</b><br>");        
  }                
}

The above else if condition is executed when the user clicked list submit button. The code should display all the items and their quantity selected by the user earlier. All the cookies sent to client earlier are called back by the server by calling getCookies() method of request object. This method returns an array of Cookie objects. All the cookies are iterated in a for loop. getName() and getValue() of Cookie class returns the first parameter (item name) and second parameter (item quantity) passed earlier to Cookie constructor.

Empty ShoppingCart:

ima

When user types some item name and item quantity.

Servlet Cookies

Output screen when List Cookies submit button is clicked (after adding few items).

Servlet Cookies

Observe the string Session ID (known as JSESSIONID) length. It is more than 30 characters.