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.5. Reading Cookie Values with a JSP

Problem

You want to read cookie values with a JSP.

Solution

Use the JSTL and its cookie implicit object to display the name and value of any cookies found in the request.

Discussion

The JSTL and its EL have a cookie implicit object (a variable that is automatically available to JSP or EL code) that you can use in JSPs to display any cookie names and values. For more information on the JSTL and EL, see Chapter 23.

You can access the cookie implicit object in JSP code this way:

${cookie}

This implicit object evaluates to a java.util.Map type whose values you can iterate over with the c:forEach JSTL tag. Each iteration of c:forEach returns a java.util.Map.Entry, which encapsulates a key/value pair. The key is the name of the cookie; the value is a javax.servlet.http.Cookie object.

Example 10-6 uses this code to retrieve a Cookie object from the Map of available cookies:

<c:forEach var="cookieVal" items="${cookie}">

The var attribute of c:forEach contains a Map.Entry object whose key is the cookie name; the value is the Cookie object. The code uses c:out tags to display the cookie names and values in the JSP. This odd syntax displays the value of each cookie:

<c:out value="${cookieVal.value.value}" />

The code cookieVal.value evaluates to the javax.servlet.http.Cookie object. The full phrase ${cookieVal.value.value} is the equivalent of calling Cookie.getValue( ).

Example 10-6. A JSP that reads cookie names and values

<%@ taglib uri="http://java.sun.com/jstl/core" ...

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