O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.3. Setting a Cookie with a JSP

Problem

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

Solution

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

Discussion

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required