[ Team LiB ] Previous Section Next Section

Recipe 10.1 Setting a Cookie with a Servlet

Problem

You want to set a cookie using a servlet.

Solution

Create the javax.servlet.http.Cookie object in a servlet, then set the cookie on a user's machine with the javax.servlet.http.HttpServletResponse.addCookie(Cookie cookie) method.

Discussion

Inside the servlet, create the Cookie by instantiating a new Cookie and calling its setter (or mutator) methods. The Cookie constructor includes the name and value for the cookie:

Cookie cookie = new Cookie("mycookie","the1cookie");

Example 10-1 creates a cookie and sets its path attribute (as in: cookie.setPath(String path)) to the name of the context path (as in /home). With this path setting, the client will not send the cookie to the server unless the client requests resources within the specified context path. The code uses HttpServletRequest.getContextPath( ) to provide the value for the cookie's path attribute.

Example 10-1. A servlet that sets a cookie and displays some cookie information
package com.jspservletcookbook;           

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

public class CookieServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    
      Cookie cookie = null;
      //Get an array of Cookies associated with this domain
      Cookie[] cookies = request.getCookies( );
      boolean newCookie = false;
    
      //Get the 'mycookie' Cookie if it exists
      if (cookies != null){
          for (int i = 0; i < cookies.length; i++){
              if (cookies[i].getName( ).equals("mycookie")){
                  cookie = cookies[i];
              } 
          }//end for
      }//end if
       
      if (cookie == null){
          newCookie=true;

          //Get the cookie's Max-Age from a context-param element
          //If the 'cookie-age' param is not set properly
          //then set the cookie to a default of -1, 'never expires'
          int maxAge;
          try{
              maxAge = new Integer(
                getServletContext( ).getInitParameter(
                  "cookie-age")).intValue( );
          } catch (Exception e) {

              maxAge = -1;
          }//try
      
          //Create the Cookie object
     
          cookie = new Cookie("mycookie",""+getNextCookieValue( ));
          cookie.setPath(request.getContextPath( ));
          cookie.setMaxAge(maxAge);
          response.addCookie(cookie);
        
      }//end if
      // get some info about the cookie
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
    
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Cookie info</title>");  
      out.println("</head>");
      out.println("<body>");
        
      out.println(
      "<h2> Information about the cookie named \"mycookie\"</h2>");
        
      out.println("Cookie value: "+cookie.getValue( )+"<br>");
      if (newCookie){
          out.println("Cookie Max-Age: "+cookie.getMaxAge( )+"<br>");
          out.println("Cookie Path: "+cookie.getPath( )+"<br>");
      }
        
        out.println("</body>");
        out.println("</html>");
    } 
    private long getNextCookieValue( ){
    
        //returns the number of milleseconds since Jan 1, 1970
        return new java.util.Date( ).getTime( );
    
    }

  public void doPost(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
      java.io.IOException {
        
        doGet(request,response);
  } 
}

Example 10-1 uses Cookie.setMaxAge(int age) to specify when the cookie will expire or be deleted by the browser. The method parameter represents the maximum number of seconds that the cookie will live on the user's machine after it is created. The example code gets the value for this method from a context-param element in web.xml, which allows a web developer to configure or optionally change this value in the deployment descriptor. Here is an example of a context-param element that provides a value for a cookie's age:

<context-param>
    <param-name>cookie-age</param-name>
    <param-value>31536000</param-value>
</context-param>

For example, if you wanted the cookie to linger for one year (365 x 24 x 60 x 60 seconds), you could use this code:

cookie.setMaxAge(31536000);

Users can delete a cookie from their machine, regardless of the maximum age that you have created for it. Some browsers provide a window into a user's cookies, with features that allow the user to remove one or more cookies. Don't assume that because you set a maximum age, the cookie will always be available on users' machines.


Example 10-1 also checks for the existence of a cookie of the same name that the code plans to give the new cookie (mycookie). If the user has not already sent the mycookie cookie, then the servlet sets a new cookie and displays some of the cookie's values afterward.

Figure 10-1 shows the servlet output.

Figure 10-1. A servlet shows information about a new cookie
figs/jsjc_1001.gif

The cookie value is arbitrarily set to a String showing a large number, just to demonstrate how to provide the value for a cookie. As many cookies need unique values, you could use a method whereby the user's email address or unique database ID is encoded and then used as the cookie value.

See Also

Recipe 10.3 on setting a cookie with a JSP; Recipe 10.4 on using a servlet to read cookies; Recipe 10.5 on reading cookie values with a JSP; Recipe 10.6 on altering or removing an existing cookie; the RFC 2109 document dealing with cookies: ftp://ftp.rfc-editor.org/in-notes/rfc2109.txt; Netscape's preliminary specification for cookies: http://wp.netscape.com/newsref/std/cookie_spec.html; the Java Cookie API: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/Cookie.html.

    [ Team LiB ] Previous Section Next Section