Home > Articles > Programming > Java

This chapter is from the book

Session Handling: Cookies

Using cookies is one of the most widely used and accepted ways to maintain a session. A cookie is a special tag identifier that your server generates and the browser accepts. Actually, it is a simple data structure consisting of name-value pairs associated with a URL, in this case, the URL to execute the servlet. For maintaining a session, the servlet stores the session identifier and other session data as a text string in the cookie.

After accepting the session cookie, the browser propagates the cookie to your servlet for every request from the browser to the servlet. A servlet can read the cookie and modify its contents at any time. If there is no cookie, the servlet detects a new session, generates a unique session identifier, and sets this value to the cookie. This is then sent back to the browser along with the response HTML page. The browser interprets the response, identifies the cookie, and sets it in the browser. After this, for every request, the browser sends this cookie containing the session identifier to the servlet.

Cookies can be transient or persistent. Transient cookies last until the browser is closed, while persistent cookies are stored by the browser on the physical disk, to be retrieved and used when the same URL is accessed by the user again. Cookies, transient or persistent, have a time limit and expire after the time limit is exceeded.

Cookies are one of the simplest and most widely used techniques for session handling. They are supported by WebLogic Server as well as all client browsers and the Servlet API.

A primary limitation of cookies is the length of data that can be stored. A maximum of 4KB of data can be stored in a cookie. This limits the amount of session data that can be stored for a user.

Browsers allow disabling of cookies. If cookie acceptance is disabled, this technique is not going to work.


If the cookie-accepting feature in the browser is disabled, the WebLogic Server detects this and automatically switches the session-handling mechanism to retrieving the session identifier from an encoded URL as long as your servlet uses the encodeURL() method for generating all URLs in the response page.

Sample Program

Now you can look at a sample program (Listing 3.3) that implements this session- handling technique. Figure 3.16 illustrates the sequence diagram for the program.

Figure 3.16 Sequence diagram for session handling using cookies.

Listing 3.3 BookShoppingServlet.java

 * Class Name:BookShoppingServlet
 * Extends:HttpServlet
 * Description:Shopping Cart Application Using cookies,
 * @author Mandar S. Chitnis, Lakshmi AM.    @version 1.1
 * Copyright (c) by Sams Publishing. All Rights Reserved.
package com.sams.learnweblogic7.servlets;

//import the utils package
import com.sams.learnweblogic7.utils.*;

//importing standard servlet packages
import javax.servlet.*;
import javax.servlet.http.*;

//import io,util, and math packages
import java.io.*;
import java.util.*;
import java.math.*;

public class BookShoppingServlet extends HttpServlet
//defining global variables to be used in this servlet

  Book book1;
  Book book2;
   Book book3;

  PrintWriter out;

  private static final int DEFAULT_ZERO_VALUE = 0;
  private static final String EXAMPLE_TYPE = "Shopping Cart Using Cookies";

//Method corresponding to post request of HTML, & called by doGet() method
  //calls the doSessionUsingCookie method internally.
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException{
    out = res.getWriter();
    writeHeaderZone(out , EXAMPLE_TYPE);
    doSessionUsingCookie(out, req, res);
  }//end of doPost

//Method called by doPost

  public void doSessionUsingCookie(PrintWriter outputObject,
      HttpServletRequest req, HttpServletResponse res){
    Hashtable shoppingCartHash = null;
    Cookie bookCookie = null;
    Cookie[] cookies = req.getCookies();
    if (cookies==null)
      bookCookie = new Cookie(book1.getBookId(),

      bookCookie = new Cookie(book2.getBookId(),

      bookCookie = new Cookie(book3.getBookId(),

    String clickedButton =
(req.getParameter("buttonName") == null)?"":req.getParameter("buttonName");

      outputObject.println("<FORM name=\"viewcart\"
          -action=\"/ShoppingApp/BookShoppingServlet\"  method=\"get\">");
      outputObject.println("<B><font face = \"Verdana\"
          color=\"blue\" size=-2><p align = \"right\">Shopping Cart
          using Cookies</p></font></B>");
      int book1Qty =
Utility.getDefaultValue(getCookieValue(cookies, book1.getBookId()),
      int book2Qty = Utility.getDefaultValue(getCookieValue(cookies,
book2.getBookId()),DEFAULT_ZERO_VALUE); int book3Qty = Utility.getDefaultValue(getCookieValue(cookies,
book3.getBookId()),DEFAULT_ZERO_VALUE); writeViewCartZone(outputObject, book1Qty, book2Qty, book3Qty); outputObject.println("<p align =\"center\"><INPUT type=\"submit\" name=\"buttonName\" value=\"Empty Shopping Cart\"></p>"); outputObject.println("</FORM>"); } else if(clickedButton.equals("add") || clickedButton.equals("")) { updateCookie(req, res, cookies,outputObject); outputObject.println("<FORM name=\"addcart\" action=\"/ShoppingApp/BookShoppingServlet\"
method=\"post\">"); outputObject.println("<B><font face = \"Verdana\" color=\"blue\" -size=-2><p align = \"right\">Shopping Cart using Cookies</p></font></B>"); writeBookListZone(outputObject); outputObject.println("<CENTER><TABLE width = 100%><TR>"); outputObject.println("<TD align = \"center\"><INPUT type=\"submit\" name=\"buttonName\" value=\"add\"></TD>"); outputObject.println("<TD align = \"center\"><INPUT type=\"submit\" name=\"buttonName\" value=\"view\"></TD>"); outputObject.println("</TR></TABLE></CENTER>"); outputObject.println("</FORM>"); } else if(clickedButton.equals("Empty Shopping Cart")){ //setting the cookie values to null and invalidating the cookies weblogic.servlet.security.ServletAuthentication.invalidateAll(req); weblogic.servlet.security.ServletAuthentication.killCookie(req); Cookie updateBookCookie = null; updateBookCookie = new Cookie(book1.getBookId(), Integer.toString(DEFAULT_ZERO_VALUE)); updateBookCookie.setMaxAge(Integer.MAX_VALUE); res.addCookie(updateBookCookie); updateBookCookie = new Cookie(book2.getBookId(), Integer.toString(DEFAULT_ZERO_VALUE)); updateBookCookie.setMaxAge(Integer.MAX_VALUE); res.addCookie(updateBookCookie); updateBookCookie = new Cookie(book3.getBookId(), Integer.toString(DEFAULT_ZERO_VALUE)); updateBookCookie.setMaxAge(Integer.MAX_VALUE); res.addCookie(updateBookCookie); outputObject.println("<FORM name=\"addcart\" -action=\"/ShoppingApp/BookShoppingServlet\" method=\"post\">"); outputObject.println("<B><font face = \"Verdana\" color=\"blue\" -size=-2><p align = \"right\">Shopping Cart using Hidden Variables</p> </font></B>"); writeBookListZone(outputObject); outputObject.println("<CENTER><TABLE width = 100%><TR>"); outputObject.println("<TD align = \"center\"><INPUT type=\"submit\" name=\"buttonName\" value=\"add\"></TD>"); outputObject.println("<TD align = \"center\"><INPUT type=\"submit\" name=\"buttonName\" value=\"view\"></TD>"); outputObject.println("</TR></TABLE></CENTER>"); outputObject.println("</FORM>"); } } public void updateCookie(HttpServletRequest req, HttpServletResponse res, Cookie[] bookCookies, PrintWriter outputObject){ Cookie bookCookie = null; int Book1Qty = Utility.getDefaultValue(getCookieValue(bookCookies,
book1.getBookId()),DEFAULT_ZERO_VALUE)+ Utility.getDefaultValue(req.getParameter("book1_qty"), DEFAULT_ZERO_VALUE); int Book2Qty = Utility.getDefaultValue(getCookieValue(bookCookies,
book2.getBookId()),DEFAULT_ZERO_VALUE)+ Utility.getDefaultValue(req.getParameter("book2_qty"), DEFAULT_ZERO_VALUE); int Book3Qty = Utility.getDefaultValue(getCookieValue(bookCookies,
book3.getBookId()),DEFAULT_ZERO_VALUE)+ Utility.getDefaultValue(req.getParameter("book3_qty"), DEFAULT_ZERO_VALUE); bookCookie = new Cookie(book1.getBookId(), Integer.toString(Book1Qty)); bookCookie.setMaxAge(Integer.MAX_VALUE); res.addCookie(bookCookie); bookCookie = new Cookie(book2.getBookId(), Integer.toString(Book2Qty)); bookCookie.setMaxAge(Integer.MAX_VALUE); res.addCookie(bookCookie); bookCookie = new Cookie(book3.getBookId(), Integer.toString(Book3Qty)); bookCookie.setMaxAge(Integer.MAX_VALUE); res.addCookie(bookCookie); } public String getCookieValue(Cookie[] bookCookies, String cookieName){ for(int i=0; i<bookCookies.length; i++) { if((bookCookies[i].getName()).equals(cookieName)) { return bookCookies[i].getValue(); } } return null; } ... }//end of BookShoppingServlet

The only difference between the code in Listing 3.3 and Listing 3.2 is the addition of the doSessionUsingCookie() method, which performs the session handling for the servlet. This method is called from the doPost() method.

The doSessionUsingCookie() method uses the Cookie class of the Servlet API to store and manipulate the session cookie. The cookie is a part of the HttpServletRequest and is retrieved by calling the getCookies() method of the HttpServletRequest object. This method returns an array of Cookie objects.

To determine whether a session exists between the servlet and the browser, the servlet checks whether the Cookie array retrieved is null. If it is null, the servlet concludes that no cookies exist between the browser and the servlet and hence creates a new session between them. The session in this case is the contents of the shopping cart. The servlet creates a new cookie for each of the books in your store by constructing a new cookie object, which takes a cookie identifier and empty shopping cart data as parameters. This is done in the line

bookCookie = new Cookie(book1.getBookId(), Integer.toString(DEFAULT_ZERO_VALUE));

The next call is to set the expiry limit of the cookie. Your cookie will be alive for a long time because the sample program sets the expiry limit to the largest integer using the setMaxAge() call:


Finally, the browser cookie is set by calling the addCookie() method on the response object:


Repeat the same steps for the other books in your store.

To determine whether the user action is Add To Cart or View Cart, retrieve the value of the buttonName parameter from the request. This is similar to what you did for the previous session-handling techniques.

For the Add To Cart function, you need to retrieve the contents of the shopping cart as well as the new user selections. This is done by calling the updateCookie() method.

To retrieve contents of the shopping cart, you will write a method getCookieValue() that takes the array of Cookie objects and the name of the cookie whose value needs to be retrieved. The getCookieValue() method iterates through the array of Cookie objects and retrieves the value of the cookie by comparing the names of the cookies in the array with the name of the cookie you are interested in:


Once you have a match, extract the value from the cookie object by calling the getValue() method on the Cookie object:

return bookCookies[i].getValue();

Once you have retrieved the cookie values, which are the shopping cart contents for each book, retrieve the user selections for each book and update your shopping cart cookie with the updated values for each book.

The following line sums the existing contents of the shopping cart in the cookie for book1 and the new user selection retrieved from the getParameter("book1_qty") call:

int Book1Qty = Utility.getDefaultValue(getCookieValue(bookCookies,
book1.getBookId()),DEFAULT_ZERO_VALUE)+ Utility.getDefaultValue(req.getParameter("book1_qty"), DEFAULT_ZERO_VALUE);

Even though the call seems complex, it is actually very simple when you know the business logic! The getDefaultValue() utility method performs the conversion from String data to a primitive int data type, as you saw earlier in the explanation for the Utility class. Similar calculations are done for the other books in your store.

Finally, you set the updated shopping cart data in the user's browser by calling the addCookie() method on the response object after creating a new cookie with the updated values. Then send the book-listing page back to the browser.

For the View Cart function, you need to retrieve the contents of the shopping cart stored in the browser. This is done by the call

int book1Qty = Utility.getDefaultValue(getCookieValue(cookies,

This is similar to the retrieval of shopping contents for the Add To Cart function. The only difference is that there will be no new user selections and hence no updates required to the cookie. You will perform similar actions for the rest of the books in your store.

Finally, you will generate the View Cart page using the writeViewCartZone() method with the retrieved shopping cart data as parameters.

Functionality to enable the user to empty the shopping cart is provided in the servlet. The emptying function is kicked off when the user clicks on the Back To Cart button. Since this session-handling technique is based on cookies, you need to destroy the cookies that were created for the user in this session. In addition, you also need to destroy the session that was created between the WebLogic Server and the browser application. This ensures that the entire session is wiped out. This is done by the call


The invalidateAll() call destroys the entire authentication session between the browser and the WebLogic Server.

Compile the Program

Since you are not adding any new classes nor are you changing the deployment location of the application, the compiling of the servlet program is similar to compiling the hidden-variables session-handling method.

Deploy the Program

There are no settings to be made in the deployment descriptor file for deploying the servlet using the cookie session-handling technique since this session handling is performed programmatically.


If your servlet is invoked from http and https (secure HTTP) requests, the servlet treats these requests within a session as different session requests since the ports used for sending the requests are different (port 80 for http and port 443 for https). To avoid this problem, WebLogic Server provides a setting that can be changed in the WebLogic Server–specific deployment descriptor file weblogic.xml. In this file, add the following deployment descriptor:


where the value yourdomain.com is the domain name of your Web site. For example, for the http://www.samspublishing.com Web site, this would be samspublishing.com.

Execute the Program

The book-listing page is invoked from the browser by calling the following URL:


InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020