Servlet Session I: Cookie API
Servlet Session I: Cookie API
Road Map
Creating Cookies
Cookie Attributes
Reading Cookies
Example 1: Basic Counter
Example 2: Tracking Multiple Cookies
Case Study: Customized Search
Engine
The Potential of Cookies
• Idea
• Servlet sends a simple name and value to client.
• Client returns same name and value when it
connects to same site (or same domain,
depending on cookie settings).
• Typical Uses of Cookies
• Identifying a user during an e-commerce
session
• Avoiding username and password
• Customizing a site
• Focusing advertising
Cookies and Focused
Advertising
Creating Cookies
Creating Cookies
Three steps to creating a new cookie:
1) Create a new Cookie Object
Cookie cookie = new Cookie (name, value);
2) Set any cookie attributes
Cookie.setMaxAge (60);
3) Add your cookie to the response object:
Response.addCookie (cookie)
We will examine each of these steps in
detail.
Sending Cookies to the Client
• Create a Cookie object.
• Call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
Cookie c = new Cookie("userID", "a1234");
// add cookie info to to response (with new updated counter as value of cookie)
response.addCookie(c);
Tracking User Access Counts
(Continued)
// print result or number of visits per browser
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title +
"</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + title + "</H1>\n" +
"<H2>This is visit number " +
count + " by this browser.</H2>\n"+
"</CENTER></BODY></HTML>");
}
}
Tracking User Access Counts
(Results) (run live)
Summary
To create a cookie:
Create a new Cookie Object
Cookie cookie = new Cookie (name, value);
Set any cookie attributes
Cookie.setMaxAge (60);
Add your cookie to the response object:
Response.addCookie (cookie)