The Servlet Cookie API

To send cookies to the client, a servlet should create one or more cookies with designated names and values with new Cookie(name, value), set any optional attributes with cookie.setXxx (readable later by cookie.getXxx),and insert the cookies into the response headers with response.addCookie(cookie).To read incoming cookies, a servlet should call request.getCookies, which returns an array of Cookie objects corresponding to the cookies the browser has associated with your site (this is null if there are no cookies in the request). In most cases, the servlet loops down this array until it finds the one whose name (getName) matches the name it had in mind, then calls getValue on that Cookie to see the value associated with that name. Each of these topics is discussed in more detail in the following sections.

Creating Cookies

You create a cookie by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain white space or any of the following characters:
[ ] ( ) = , ” / ? @ : ;

Cookie Attributes

Before adding the cookie to the outgoing headers, you can set various characteristics of the cookie by using one of the following setXxx methods, where Xxx is the name of the attribute you want to specify. Each setXxx method has a corresponding getXxx method to retrieve the attribute value. Except for name and value, the cookie attributes apply only to outgoing cookies from the server to the client; they aren’t set on cookies that come from the browser to the server.

public String getComment()
public void setComment(String comment)

These methods look up or specify a comment associated with the cookie. With version 0 cookies (see the upcoming subsection on getVersion and setVersion), the comment is used purely for informational purposes on the server; it is not sent to the client.

public String getDomain()
public void setDomain(String domainPattern)

These methods get or set the domain to which the cookie applies. Normally, the browser only returns cookies to the exact same hostname that sent them. You can use setDomain method to instruct the browser to return them to other hosts within the same domain. To prevent servers setting cookies that apply to hosts outside their domain, the domain specified is required to start with a dot (e.g., .prenhall.com), and must contain two dots for noncountry domains like .com, .edu and .gov; and three dots for country domains like
.co.uk and .edu.es. For instance, cookies sent from a servlet at bali.vacations.com would not normally get sent by the browser to pages at mexico.vacations.com. If the site wanted this to happen, the servlets could specify cookie.setDomain(“.vacations.com”).

public int getMaxAge()
public void setMaxAge(int lifetime)

These methods tell how much time (in seconds) should elapse before the cookie expires. A negative value, which is the default, indicates that the cookie will last only for the current session (i.e., until the user quits
the browser) and will not be stored on disk. See the LongLivedCookie class (Listing 8.4), which defines a subclass of Cookie with a maximum age automatically set one year in the future. Specifying a value of 0
instructs the browser to delete the cookie.

public String getName()
public void setName(String cookieName)

This pair of methods gets or sets the name of the cookie. The name and the value are the two pieces you virtually always care about. However, since the name is supplied to the Cookie constructor, you rarely need to call setName. On the other hand, getName is used on almost every cookie received on the server. Since the getCookies method of Http-ServletRequest returns an array of Cookie objects, it is common to loop down this array, calling getName until you have a particular name, then check the value with getValue.

public String getPath()
public void setPath(String path)

These methods get or set the path to which the cookie applies. If you don’t specify a path, the browser returns the cookie only to URLs in or below the directory containing the page that sent the cookie. For example, if the server sent the cookie from http://ecommerce.site.com/toys/specials.html, the browser would send the cookie back when connecting to http://ecommerce.site.com/toys/bikes/beginners.html, but not to http://ecommerce.site.com/cds/classical.html. The setPath method can be used to specify something more general. For example, someCookie.setPath(“/”) specifies that all pages on the server should receive the cookie. The path specified must include the current page; that is, you may specify a more general path than the default, but not a more specific one. So, for example, a servlet at http://host/store/cust-service/request could specify a path of /store/ (since /store/ includes /store/cust-service/) but not a path of /store/cust-service/returns/ (since this directory does not include /store/cust-service/).

public boolean getSecure()
public void setSecure(boolean secureFlag)

This pair of methods gets or sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e., SSL) connections. The default is false; the cookie should apply to all connections.

public String getValue()
public void setValue(String cookieValue)

The getValue method looks up the value associated with the cookie; the setValue method specifies it. Again, the name and the value are the two parts of a cookie that you almost always care about, although in a few cases, a name is used as a boolean flag and its value is ignored (i.e.,the existence of a cookie with the designated name is all that matters).

public int getVersion()
public void setVersion(int version)

These methods get/set the cookie protocol version the cookie complies with. Version 0, the default, follows the original Netscape specification (http://www.netscape.com/newsref/std/cookie_spec.html). RFCs from the archive sites listed at http://www.rfc-editor.org/).

Placing Cookies in the Response Headers

The cookie is inserted into a Set-Cookie HTTP response header by means of the addCookie method of HttpServletResponse. The method is called addCookie, not setCookie, because any previously specified Set-Cookie headers are left alone and a new header is set.

Here’s an example:

Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // 1 year
response.addCookie(userCookie);

Reading Cookies from the Client

To send cookies to the client, you create a Cookie, then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, you call getCookies on the HttpServletRequest. This call returns an array of Cookie objects corresponding to the values that came in
on the Cookie HTTP request header. If there are no cookies in the request, getCookies returns null. Once you have this array, you typically loop down it, calling getName on each Cookie until you find one matching the name you have in mind. You then call getValue on the matching Cookie and finish with some processing specific to the resultant value.

Examples of Setting and Reading Cookies
SetCookies.java

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Sets six cookies: three that apply only to the current
* session (regardless of how long that session lasts)
* and three that persist for an hour (regardless of
* whether the browser is restarted).
*/
public class SetCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
for(int i=0; i<3; i++) {
// Default maxAge is -1, indicating cookie
// applies only to current browsing session.
Cookie cookie = new Cookie("Session-Cookie " + i,
"Cookie-Value-S" + i);
response.addCookie(cookie);
cookie = new Cookie("Persistent-Cookie " + i,
"Cookie-Value-P" + i);
// Cookie is valid for an hour, regardless of whether
// user quits browser, reboots computer, or whatever.
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Setting Cookies";
out.println
(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1 ALIGN="CENTER">" + title + "</H1>n" +
"There are six cookies associated with this page.n" +
"To see them, visit then" +
"<A HREF="/servlet/coreservlets.ShowCookies">n" +
"<CODE>ShowCookies</CODE> servlet</A>.n" +
"<P>n" +
"Three of the cookies are associated only with then" +
"current session, while three are persistent.n" +
"Quit the browser, restart, and return to then" +
"<CODE>ShowCookies</CODE> servlet to verify thatn" +
"the three long-lived ones persist across sessions.n" +
"</BODY></HTML>");
}
}

ShowCookies.java

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Creates a table of the cookies associated with
* the current page.
*/
public class ShowCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Active Cookies";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1 ALIGN="CENTER">" + title + "</H1>n" +"<TABLE BORDER=1 ALIGN="CENTER">n" +
"<TR BGCOLOR="#FFAD00">n" +
" <TH>Cookie Namen" +
" <TH>Cookie Value");
Cookie[] cookies = request.getCookies();
Cookie cookie;
for(int i=0; i<cookies.length; i++) {
cookie = cookies[i];
out.println("<TR>n" +
" <TD>" + cookie.getName() + "n" +
" <TD>" + cookie.getValue());
}
out.println("</TABLE></BODY></HTML>");
}
}

Java Cookie Example

You can write cookies using the HttpServletResponse object like this:

Cookie cookie = new Cookie("myCookie", "myCookieValue");
response.addCookie(cookie);

As you can see, the cookie is identified by a name, “myCookie”, and has a value, “myCookieValue”. Thus, you can add many different cookies with different identifies (names). It’s a bit like a Hashtable.
Whenever the the browser accesses the web application it submits the cookies stored on the client machine to the web application. Only cookies stored by the accessed web application are submitted. Cookies from other web applications are not submitted.

Reading Cookies Sent From the Browser

You can read the cookies via the HttpServletRequest like this:

Cookie[] cookies = request.getCookies();

Note: the getCookies() method may return null!
Now you can iterate through the array of cookies and find the cookies you need. Unfortunately there is no way to obtain a cookie with a specific name. The only way to find that cookie again is to iterate the Cookie[] array and check each cookie name. Here is an example:

Cookie[] cookies = request.getCookies();

String userId = null;
for(Cookie cookie : cookies){
    if("uid".equals(cookie.getName())){
        userId = cookie.getValue();
    }
}

This example finds the cookie with the name “uid” and stores its value in the
If you need to access more than one cookie, you could iterate the Cookie[] array once, and put the Cookie instances into a Map, using the cookie name as key, and the Cookie instance as value. Here is how that could look:

Map cookieMap = new HashMap();
Cookie[] cookies = request.getCookies();

for(Cookie cookie : cookies){
    cookieMap.put(cookie.getName(), cookie);
}

After this code is executed, you can now access the cookies in the cookieMap using the cookie names as keys (cookieMap.get(“cookieName”)).

Cookie Expiration

One important Cookie setting is the cookie expiration time. This time tells the browser receiving the cookie how long time it should keep the cookie before deleting it.
You set the cookie expiration time via the setMaxAge() method. This method takes the number of seconds the cookie is to live as parameter. Here is an example:

Cookie cookie = new Cookie("uid", "123");
cookie.setMaxAge(24 * 60 * 60);  // 24 hours. 
response.addCookie(cookie);

This example first creates a Cookie instance with the name “uid” and the value “123”. Second, it sets the expiration to 24 hours using the setMaxAge() method. 24 hours is 60 seconds x 60 minutes x 24 hours (24 x 60 x 60). Finally the example sets the cookie on the HttpServletResponse object, so the cookie is included in the response sent to the browser.

Removing Cookies

Sometimes you may want to remove a cookie from the browser. You do so by setting the cookie expiration time. You can set the expiration time to 0 or -1. If you set the expiration time to 0 the cookie will be removed immediately from the browser. If you set the expiration time to -1 the cookie will be deleted when the browser shuts down.
Here is an example:

Cookie cookie = new Cookie("uid", "");
cookie.setMaxAge(0); 
response.addCookie(cookie);

If the browser already has a cookie stored with the name “uid”, it will be deleted after receiving the cookie with the same name (“uid”) with an expiration time of 0. If the browser did not already have the cookie stored, this new cookie is just thrown out immediately since its expiration time is 0.

Additional Cookie Settings

A cookie has various other settings you can modify and access in addition to its expiration. Check out the Cookie class JavaDoc for more details.

Cookie Use Cases

Cookies are most often used to store user specific information, like e.g. a unique user ID (for anonymous users which do not login), a session ID, or user specific settings you do not want to store in your web applications database (if it has one).

 

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next