Servlets

Date: 12/July/2003

How to manage the client state using cookies

After completing this How-to you should be able to:
  •   Identify different mechanisms in which clients' requests can be tracked.
  •   Save information on the client system using cookies.
  •   Retrieve cookie information from the client system

Introduction

The main purpose of cookies is to identify users and possibly prepare customized Web pages for them. When you enter a Web site using cookies, you may be asked to fill out a form providing such information as your name and interests. This information is packaged into a cookie and sent to your Web browser which stores it for later use. The next time you go to the same Web site, your browser will send the cookie to the Web server. The server can use this information to present you with custom Web pages. So, for example, instead of seeing just a generic welcome page you might see a welcome page with your name on it.

Pre-requisites for running the example

You will need the following to run this example -

  • Oracle Containers for Java (OC4J 9.0.3) . This can be downloaded from here.
    or
    Oracle9i JDeveloper. This can be downloaded from here
  • Apache Ant 1.4.x, if you are going to deploy on OC4J (Download from Apache).

Description

Java Servlets offer two different ways of retrieving information about the client state -

  • Session - HttpSession implements necessary methods like getAttribute() and setAttribute() which enable tracking client's service request history.
  • Cookies - In this document we will discuss this approach to manage client state.

Cookies are a general mechanism which server side programs can use to both store and retrieve information on the client side of the connection. Any future HTTP requests made by the client to the same server side program will result in the retrieval of client state information stored on the earlier visit. Cookies are embedded in the HTTP response sent back to the client from the application server and are saved on the client's file system.

Let us now understand what cookies can and cannot do using an example. We will assume a simple login page where the user is expected to provide username and password to login to the application. The first time the user provides username and password, these values are stored in a cookie. The next time the user tries to login in, the login information is retrieved from the cookie and the login fields are defaulted with these values.

Setting Cookies

Here is the code snippet for initializing a cookie and adding the same to the response object.

  1. .....
  2. Cookie cookie = new Cookie("otncookiename",userName);
  3. cookie.setMaxAge(86400);
  4. response.addCookie(cookie);
  5. Cookie onemorecookie = new Cookie("otncookiepassword",password);
  6. onemorecookie.setMaxAge(86400);
  7. response.addCookie(onemorecookie);
  8. .....

As shown above construction of a Cookie object requires a name value pair . In the above example, we create two cookies with names otncookiename and otncookiepassword. These store the username and password supplied by the user. Another thing to be noted is the method setMaxAge. This takes as int as parameter which signifies the expiration time for the cookie. What this means is that if a positive value x is specified for setMaxAge the cookie will expire after x seconds. If a negative value is specified the cookie is not stored persistently and will be deleted when the Web browser exits. In our example we have specified a value of 86400 seconds for the cookie, so the cookie will be stored for a day.

Retrieving a cookie value

Here is the code snippet for selecting cookie values from the request object.

  1. ......
  2. Cookie[] cookieArray = request.getCookies();
  3. if( cookieArray != null) {
  4.   for( int i = cookieArray.length-1; i >= 0; i-- ) {
  5.     Cookie cookie = cookieArray[i];
  6.     System.out.println("Cookie name is " + cookie.getName());
  7.     System.out.println("Cookie value is " + cookie.getValue());
  8.   }
  9. }
  10. ......

 

As shown above cookie values stored can be retrieved as an array from the request object. You can only retrieve cookies set by your web server. After getting an array of cookies, you can loop through the array and access the cookie name and values.

Limitation of Cookies

In this section we will see some restrictions on the use of cookies

  1. The browser should be enabled to accept cookies
  2. Cookie values must never have spaces, commas or semicolons
  3. Cookies can store upto 4KB of value

Running the Sample

The complete source code for this sample is available here. This section discusses the instruction to run the sample application

Step 1 Unjar Cookies.jar using Winzip, or using the following command:

> jar xvf Cookies.jar

This creates a directory Cookies.

Step 2

If you are using JDeveloper then, follow these steps

  • Open Oracle9i JDeveloper and use File/Open option to select the Cookies.jws from the Cookies directory.
  • Next, select Project/Make Cookies.jpr from main menu.
  • Now, select Run/Run Cookies.jpr from main menu to run the application.
Step 3 If you are using standalone OC4J to run the sample application then follow these steps
  • On command prompt , set the environment variables ANT_HOME,JAVA_HOME,OC4J_HOME and OC4J_HOST
    e.g.:
    d:\Cookies\set ANT_HOME=d:\ant141
    d:\Cookies\set JAVA_HOME=d:\jdk1.3.1_01
    d:\Cookies\set OC4J_HOME=d:\oc4j903
    d:\Cookies\set OC4J_HOST=localhost:23791
  • Start OC4J
  • Run ant
  • Access the application from any browser : http://<hostname>:<port>/cookieInfo/servlet/cookie


Please enter your comments about this sample in the OTN Sample Code Discussion Forum.


E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy