Recipe 10.3 Setting a Cookie with a JSP


You want to use a JSP to set a cookie on a client.


Wrap a JavaBean around the servlet API for creating cookies. Then use the bean in the JSP with the jsp:useBean standard action.


A JSP can use a JavaBean to create the cookie and set the cookie on the client. Example 10-3 creates an instance of a JavaBean of type com.jspservletcookbook.CookieBean using the jsp:useBean standard action. Then the JSP sets a few bean properties. The bean will pass through the property values to the cookie that it is generating for the JSP. The JSP uses jsp:setProperty to set the following cookie properties:

  • The cookie name ( bakedcookie in the code).

  • The maximum number of seconds the browser will hold on to the cookie ( roughly one year in Example 10-2). This number is converted to a readable future date for the cookie's Expires attribute.

  • The path on the server associated with this cookie. Once the JSP has sent this cookie to the client, the client will return the associated cookie only in the request headers for requests that contain the specified context path (such as /home ). For example, if the cookie is set by the JSP file to /home/cookieSet.jsp , only requests for resources in /home will include a Cookie header.

Example 10-3. A JSP that sends a cookie to a client
  <jsp:useBean id="cookieBean" class="com.jspservletcookbook.CookieBean" /> <jsp:setProperty name="cookieBean" property="name"  value="bakedcookie" /> <%-- set 'Expires' attribute to about one year from now --%> <jsp:setProperty name="cookieBean" property="maxAge"  value=   "<%= (365*24*60*60) %>" /> <jsp:setProperty name="cookieBean" property="path"  value="<%= request.getContextPath( )  %>" /> <jsp:setProperty name="cookieBean" property="cookieHeader"  value="<%= response %>" />  <html> <head><title>Cookie Maker</title></head> <body> <h2>Here is information about the new cookie</h2>  Name: <jsp:getProperty name="cookieBean" property="name" /><br> Value: <jsp:getProperty name="cookieBean" property="value" /><br> Path: <jsp:getProperty name="cookieBean" property="path" />  </body> </html> 

The JSP passes along the HttpServletResponse object to its wrapper bean, so that the bean can call response.addCookie(Cookie cookie) to send the client the new cookie. The response object is passed to the bean using this code (see the setCookieHeader( ) method in Example 10-4):

 <jsp:setProperty name="cookieBean" property="cookieHeader"  value=     "<%= response %>" /> 

The bottom of the JSP displays some of the new cookie's values. Figure 10-2 shows the JSP's output in a web browser. Repeatedly requesting the JSP will overwrite the existing cookie with a new one.

Figure 10-2. A JSP shows information about a new cookie

Example 10-4 shows the code for the CookieBean itself, which is rather lengthy due to all the getter and setter methods .

This JavaBean class must be placed in the WEB-INF/classes directory of the web application (including a directory structure that matches the bean's package name) so that the web container can load the class. The bean could also be archived in a JAR file that is placed in WEB-INF/lib ; however, the JAR would still have to contain a directory structure that matches the bean's package name.

You can set the cookie value in the JSP (which is not done in Example 10-3) by calling the bean's setValue(String value) method via jsp:setProperty :

 <jsp:setProperty name="cookieBean" property="value"  value="newvalue" /> 

The bean has to import the Cookie and HttpServletResponse classes, because it uses them to make the new cookie, then send the cookie to the client. Example 10-4 wraps its own methods around some of the Cookie class methods, such as setValue( ) and setMaxAge( ) .

Example 10-4. A JavaBean for making cookies
 package com.jspservletcookbook;  import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Cookie;  public class CookieBean {  private Cookie cookie = null;  public CookieBean( ){} //set the cookie name  public void setName(String name){     if (name == null  (name.equals("")))         throw new IllegalArgumentException(           "Invalid cookie name set in: "+getClass( ).getName( ));          cookie = new Cookie(name,""+new java.util.Date( ).getTime( )); } //set the cookie value public void setValue(String value){  if (value == null  (value.equals("")))         throw new IllegalArgumentException(           "Invalid cookie value set in: "+getClass( ).getName( ));          if (cookie != null)         cookie.setValue(value); } public void setMaxAge(int maxAge){          if (cookie != null)         cookie.setMaxAge(maxAge); } public void setPath(String path){  if (path == null  (path.equals("")))         throw new IllegalArgumentException(           "Invalid cookie path set in: "+getClass( ).getName( ));          if (cookie != null)         cookie.setPath(path); } public void setCookieHeader(HttpServletResponse response){     if (response == null )         throw new IllegalArgumentException(           "Invalid HttpServletResponse set in: "+getClass( ).getName( ));     if (cookie != null)         response.addCookie(cookie); }  public String getName( ){     if (cookie != null)        return cookie.getName( );     else        return "unavailable";         }         public String getValue( ){     if (cookie != null)        return cookie.getValue( );     else        return "unavailable";         }         public String getPath( ){     if (cookie != null)        return cookie.getPath( );     else        return "unavailable";         } } 

If the JSP fails to use jsp:setProperty to call the bean's setCookieHeader(HttpServletResponse response) method, then the cookie is created but never included in the response headers sent to the client. In this design, you allow the user to set some optional cookie attributes (such as Path ) before she explicitly sends the cookie as part of the response.

See Also

Recipe 10.1 on setting a cookie with a servlet; Recipe 10.2 on creating an array from all of the request's cookies; 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:; Netscape's preliminary specification for cookies:; the Java Cookie API:

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: