Home > Articles > Programming > Java

  • Print
  • + Share This

Working with Cookies

One of the more elegant solutions to session tracking is the use of persistent cookies. Netscape first introduced cookies in one of the company's first versions of Netscape Navigator.

A cookie is a keyed piece of data that is created by the server and stored by the client browser. Browsers maintain their own list of unique cookies. This makes cookies a very viable solution for session tracking.

The Servlet API provides built-in support for cookies. It does this through the use of the Cookie class and the HttpServletResponse.addCookie() and HttpServletRequest.getCookies() methods.

The Cookie class encapsulates persistent cookies as defined by RFC 2109. The prototype for the Cookie's constructor takes a String representing the unique name of the cookie and a String representing the value of the cookie, and it is listed as follows:

public Cookie(String name, String value)

The Cookie class also provides accessors used to get and set the values of the cookie. Listing 5.2 contains an example of using cookies to perform session handling.

Listing 5.2 CookieServlet.java

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

public class CookieServlet extends HttpServlet {
//Initialize global variables

 public void init(ServletConfig config)
  throws ServletException {

  super.init(config);
 }

 private String getCurrentUser(String value) {

  String userName = new String("");

  // This would normally be a Select from a database or
  // other storage area.
  if ( value.equals("564XX892") ) {

   userName = new String("Bob");
  }
  return userName;
 }

 //Process the HTTP Get request
 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {

  // Get the list of Cookies stored in the request
  Cookie[] cookieList = request.getCookies();
  String user = null;
  String responseString = null;

  if ( cookieList != null ) {

   // Cookies found, let's get the session id
   for ( int x = 0; x < cookieList.length; x++ ) {

    String name = cookieList[x].getName();

    if ( name.equals("session_id") ) {

     // Get the user based on the session id
     user = getCurrentUser(cookieList[x].getValue());
     break;
    }
   }
  }

  if ( user == null ) {

   // Let's create a cookie that represents a unique
   // session id.
   response.addCookie(new Cookie("session_id", "564XX892"));
   responseString = new String("Welcome to our site, " +
    "we have created a session for you.");
  }
  else {

   responseString = new String("Hello : " + user);
  }

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();

  out.println("<html>");
  out.println("<head><title>CookieServlet</title></head>");

  out.println("<body>");

  out.println(responseString);
  
  out.println("</body></html>");
  out.close();
 }

 //Get Servlet information
 public String getServletInfo() {
 
  return "CookieServlet Information";
 }
}

Every time the CookieServlet services a request, it checks for cookies in the HttpServletRequest. It does this by calling the HttpServletRequest.getCookies() method. If the request does contain cookies, the servlet will iterate over the list of cookies looking for a cookie with the name session_id.

If the request contains no cookies or the list of cookies does not contain a cookie named session_id, you create one and add it to the response. The code snippet that does this is listed as follows:

response.addCookie(new Cookie("session_id", "564XX892"));

NOTE

Cookies are stored in the response as HTTP headers. Therefore, you must add cookies to the response before adding any other content.

The best way to test this functionality is to open your browser to the CookieServlet. The first time it runs, you should get a response that says "Welcome to our site, we have created a session for you." After you get this message, click the Refresh button. You should see a new response that says "Hello : Bob." The servlet can now identify the user "Bob" by the session ID stored as a cookie.

NOTE

If you have trouble running this example, make sure the use of cookies is enabled in your browser.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.