0% found this document useful (0 votes)
75 views26 pages

Servlet Session I: Cookie API

To read cookies from a request: 1. Get all cookies from the request using request.getCookies() 2. Iterate through the cookies array to find the desired cookie 3. Extract the cookie name and value using getName() and getValue() To create and send a cookie: 1. Construct a new Cookie object, setting the name and value 2. Optionally set attributes like maxAge 3. Add the cookie to the response using response.addCookie() Cookies can be used to track users and store information to recognize returning visitors.

Uploaded by

Smita Borkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views26 pages

Servlet Session I: Cookie API

To read cookies from a request: 1. Get all cookies from the request using request.getCookies() 2. Iterate through the cookies array to find the desired cookie 3. Extract the cookie name and value using getName() and getValue() To create and send a cookie: 1. Construct a new Cookie object, setting the name and value 2. Optionally set attributes like maxAge 3. Add the cookie to the response using response.addCookie() Cookies can be used to track users and store information to recognize returning visitors.

Uploaded by

Smita Borkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 26

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");

• Set the maximum age.


• To tell browser to store cookie on disk instead of just in
memory, use setMaxAge (argument is in seconds)
c.setMaxAge(60*60*24*7); // One week

• Place the Cookie into the HTTP response


• Use response.addCookie.
• If you forget this step, no cookie is sent to the browser!
response.addCookie(c);
1. Cookie Constructor
 You create a new cookie by calling the
Cookie constructor and specifying:
 Name
 Value
 Example:
 Cookie cookie = new Cookie (“school”, “NYU”);
 Neither the name nor the value should
contain whitespace or any of the following
characters:
 []()=,“/?@;
2. Set Cookie Attributes
 Before adding your cookie to the Response
object, you can set any of its attributes.
 Attributes include:
 Name/Value
 Domain
 Maximum Age
 Path
 Version
Cookie Name
public String getName();
public void setName (String name);
 You rarely call setName() directly, as
you specify the name in the cookie
constructor.
 getName() is useful for reading in
cookies.
Cookie Age
public int getMaxAge ();
public void setMaxAge (int lifetime);
 In general there are two types of cookies:
 Session Cookies: Temporary cookies that expire
when the user exits the browser.
 Persistent Cookies: Cookies that do not expire
when the user exits the browser. These cookies
stay around until their expiration date, or the user
explicitly deletes them.
Cookie Expiration
 The setMaxAge () method tells the browser
how long (in seconds) until the cookie
expires.
 Possible values:
 Negative Value (-1) (default): creates a session
cookie that is deleted when the user exits the
browser.
 0: instructs the browser to delete the cookie.
 Positive value: any number of seconds. For
example, to create a cookie that lasts for one hour,
setMaxAge (3600);
3. Add Cookies to Response
 Once you have created your cookie, and set
any attributes, you add it to the response
object.
 By adding it to the response object, your
cookie is transmitted back to the browser.
 Example:
Cookie school = new Cookie (“school”, “NYU”);
school.setMaxAge (3600);
response.addCookie (school);
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");

• Set the maximum age.


• To tell browser to store cookie on disk instead of just in
memory, use setMaxAge (argument is in seconds)
c.setMaxAge(60*60*24*7); // One week

• Place the Cookie into the HTTP response


• Use response.addCookie.
• If you forget this step, no cookie is sent to the browser!
response.addCookie(c);
Reading Cookies
Reading Cookies
 To create cookies, add them to the response
object.
 To read incoming cookies, get them from the
request object.
 HttpServletRequest has a getCookies()
method.
 Returns an array of cookie objects. This includes
all cookies sent by the browser.
 Returns a zero-length array if there are no
cookies.
getValue/setValue
•getValue/setValue
–Gets/sets value associated with cookie.
–For new cookies, you supply value to
constructor, not to setValue.
–For incoming cookie array, you use getName
to find the cookie of interest, then call
getValue on the result.
–If you set the value of an incoming cookie,
you still have to send it back out with
response.addCookie.
Reading Cookies
 Once you have an array of cookies, you
can iterate through the array and extract
the one(s) you want.
 Our next few examples illustrate how
this is done.
Example 1: RepeatVisitor.java
 This servlet checks for a unique cookie,
named “repeatVisitor”.
 If the cookie is present, servlet says
“Welcome Back”
 Otherwise, servlet says “Welcome aboard”.
 Example: Listing 8.1
Using Cookies to Detect
First-Time Visitors
public class RepeatVisitor extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
boolean newbie = true;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie c = cookies[i];
if((c.getName().equals("repeatVisitor"))&&
(c.getValue().equals("yes"))) {
newbie = false;
break;
}
}
}
Using Cookies to Detect
First-Time Visitors (Continued)
String title;
if (newbie) {
Cookie returnVisitorCookie =
new Cookie("repeatVisitor", "yes");
returnVisitorCookie.setMaxAge(60*60*24*365);
response.addCookie(returnVisitorCookie);
title = "Welcome Aboard";
} else {
title = "Welcome Back";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
… // (Output page with above title)
Using Cookies to Detect
First-Time Visitors (Results)
(run example)
Tracking User Access Counts
public class ClientAccessCounts extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// utility return cookie value(representing counter) as a string


// “10”) for cookie name “accessCount”).
//If no value, return default “1”

String countString = CookieUtilities.getCookieValue(request,


"accessCount", "1");
int count = 1;
try {
// convert string value “1” to integer
count = Integer.parseInt(countString); // convert count to integer
} catch(NumberFormatException nfe) { }

LongLivedCookie c = new LongLivedCookie("accessCount",


String.valueOf(count+1)); // increment counter by 1

// 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)

You might also like