2010 Marty Hall
H dli Cookies
Handling
C ki
Originals of Slides and Source Code for Examples:
[Link]
Customized Java EE Training: [Link]
2
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2010 Marty Hall
For live Java EE training, please see training courses
at [Link]
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
g
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP,
JSP and this tutorial.
tutorial Available at public
venues,Customized
or customized
Java EE Training:
versions
[Link]
can be held on-site at your
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
organization. Contact hall@[Link] for details.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
Understanding the benefits and drawbacks
off cookies
ki
Sending outgoing cookies
Receiving
R
i i incoming
i
i
cookies
ki
Tracking repeat visitors
Specifying
S
if i
cookie
ki attributes
tt ib t
Differentiating between session cookies and
persistent cookies
Simplifying cookie usage with utility classes
Modifying cookie values
Remembering user preferences
4
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,
domain depending on cookie
settings).
Typical
yp
Uses of Cookies
Identifying a user during an e-commerce session
Servlets have a higher-level API for this task. In general,
session-tracking
session
tracking (next lecture) is better for short
short-term
term
tracking of user information.
Avoiding username and password
Customizing
C t i i a site
it
Focusing advertising
5
Cookies and Focused
Advertising
[Link] home page for
repeat visitor. Books shown
are based on prior history.
[Link] home page
for new visitor or visitor
with cookies disabled.
Cookies and Privacy
FoxTrot 1998 Bill Amend.
Amend Reprinted with permission of
Universal Press Syndicate. All rights reserved.
Some Problems with Cookies
The problem is privacy, not security.
Servers can remember your previous actions
If you give out personal information, servers can link that
information to your previous actions
Servers can share cookie information through use of a
cooperating third party like [Link]
Poorly designed sites store sensitive information like credit
card numbers directly in cookie
JavaScript bugs let hostile sites steal cookies (old browsers)
Moral for servlet authors
If coo
cookies
es are
a e not
ot critical
c t ca to your
you task,
tas , avoid
avo d se
servlets
v ets tthat
at
totally fail when cookies are disabled
Dont put sensitive info in cookies
Manually Deleting Cookies
(To Simplify Testing)
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"
Cookie( userID , "a1234");
a1234 );
Set the maximum age.
To tell browser to store cookie on disk instead of just in
memory, use setMaxAge (argument is in seconds)
[Link](60*60*24*7); // One week
Place the Cookie into the HTTP response
Use [Link].
If you forget this step, no cookie is sent to the browser!
[Link](c);
10
Reading Cookies from the Client
Call [Link]
This yields an array of Cookie objects.
objects
Loop down the array, calling getName on each
entry until you find the cookie of interest
Use the value (getValue) in application-specific way.
11
String cookieName = "userID";
Cookie[] cookies = [Link]();
if (cookies != null) {
for(Cookie
(
cookie: cookies)
) {
if ([Link]([Link]())) {
doSomethingWith([Link]());
}
}
}
Using Cookies to Detect
First-Time Visitors
12
@WebServlet("/repeat-visitor")
public class RepeatVisitor extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException
ServletException, IOException {
boolean newbie = true;
Cookie[] cookies = [Link]();
if (
(cookies
ki
!
!= null)
ll) {
for(Cookie c: cookies) {
if (([Link]().equals("repeatVisitor")) &&
(
([Link]().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);
[Link](60*60*24*365);
[Link](returnVisitorCookie);
title = "Welcome Aboard";
} else
l
{
title = "Welcome Back";
}
[Link]("text/html");
(
/
)
PrintWriter out = [Link]();
// (Output page with above title)
13
Using Cookies to Detect
First-Time Visitors (Results)
14
Using Cookie Attributes
getDomain/setDomain
Lets you specify domain to which cookie applies. Current
host must be part of domain specified.
getMaxAge/setMaxAge
Gets/sets the cookie expiration time (in seconds). If you
fail to set this, cookie applies to current browsing session
only.
l See
S LongLivedCookie
L
Li dC ki helper
h l
class
l given
i
earlier.
li
getName
Gets the cookie name.
name There is no setName method; you
supply name to constructor. For incoming cookie array,
you use getName to find the cookie of interest.
15
Using Cookie Attributes
getPath/setPath
Gets/sets the path to which cookie applies. If unspecified,
cookie applies to URLs that are within or below directory
p g
containingg current page.
getSecure/setSecure
Gets/sets flag indicating whether cookie should apply
only
l to
t SSL connections
ti
or to
t all
ll connections.
ti
getValue/setValue
16
Gets/sets value associated with cookie.
cookie For new cookies,
cookies
you supply value to constructor, not to setValue. For
incoming cookie array, you use getName to find the
cookie of interest
interest, then call getValue on the result.
result If you
set the value of an incoming cookie, you still have to send
it back out with [Link].
Differentiating Session Cookies
from Persistent Cookies
17
@WebServlet("/cookie-test")
public class CookieTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException
ServletException, IOException {
for(int i=0; i<3; i++) {
Cookie cookie =
new Cookie("Session-Cookie-"
C ki ("S
i
C ki " + i
i,
"Cookie-Value-S" + i);
// No maxAge (ie maxAge = -1)
[Link](cookie);
(
)
cookie = new Cookie("Persistent-Cookie-" + i,
"Cookie-Value-P" + i);
[Link](3600);
[Link](cookie);
}
Differentiating Session Cookies
from Persistent Cookies (Cont)
// Start an HTML table
Cookie[] cookies = request
[Link]();
getCookies();
if (cookies == null) {
[Link]("<TR><TH COLSPAN=2>No cookies");
} else {
for(Cookie cookie: cookies) {
[Link]
("<TR>\ " +
("<TR>\n"
" <TD>" + [Link]() + "\n" +
" <TD>" + [Link]());
}
}
[Link]("</TABLE></BODY></HTML>");
}
}
18
Differentiating Session Cookies
from Persistent Cookies
Result of initial visit to CookieTest servlet
Same result as when visiting the servlet, quitting the
browser, waiting an hour, and revisiting the servlet.
19
Differentiating Session Cookies
from Persistent Cookies
Result of revisiting CookieTest within an hour
off original
i i l visit
i it (same
(
browser
b
session)
i )
I.e., browser stayed open between the original visit and
the visit shown here
20
Differentiating Session Cookies
from Persistent Cookies
Result of revisiting CookieTest within an hour
off original
i i l visit
i it (different
(diff
t browser
b
session)
i )
I.e., browser was restarted between the original visit and
the visit shown here
here.
21
Utility: Finding Cookies with
Specified Names
22
public class CookieUtilities {
public static String getCookieValue
(HttpServletRequest request,
String cookieName,
String defaultValue) {
Cookie[] cookies = [Link]();
if (cookies != null) {
for(Cookie cookie: cookies) {
if ([Link]([Link]())) {
return([Link]());
}
}
}
(
);
return(defaultValue);
}
Utility: Creating Long-Lived
Cookies
public class LongLivedCookie extends Cookie {
public static final int SECONDS_PER_YEAR =
60*60*24*365;
public LongLivedCookie(String name, String value) {
super(name, value);
setMaxAge(SECONDS PER YEAR);
setMaxAge(SECONDS_PER_YEAR);
}
}
23
Applying Utilities:
RepeatVisitor2
24
@WebServlet("/repeat-visitor2")
public class RepeatVisitor2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
boolean newbie = true;
String value =
[Link](request,
"repeatVisitor2",
"no");
if ([Link]("yes")) {
newbie = false;
}
String
g title;
if (newbie) {
LongLivedCookie returnVisitorCookie =
new LongLivedCookie("repeatVisitor2", "yes");
[Link](returnVisitorCookie);
p
(
)
title = "Welcome Aboard";
} else {
title = "Welcome Back";
}
Applying Utilities:
RepeatVisitor2
25
Modifying Cookie Values
Replacing a cookie value
Send the same cookie name with a different cookie value
Reusing incoming Cookie objects
N
Need
d tto callll [Link];
ddC ki
merely calling setValue is not sufficient.
Also need to reapply any relevant cookie attributes by
calling
lli setMaxAge,
tM A
setPath,
tP th [Link]
t
ki attributes
tt ib t are nott
specified for incoming cookies.
Usually not worth the bother, so new Cookie object used
Instructing the browser to delete a cookie
Call setMaxAge(0)
26
Tracking User Access Counts
27
@WebServlet("/client-access-counts")
public class ClientAccessCounts extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String countString =
[Link](request,
"accessCount",
,
"1");
int count = 1;
try
y {
count = [Link](countString);
} catch(NumberFormatException nfe) { }
LongLivedCookie c =
new LongLivedCookie("accessCount",
[Link](count+1));
[Link](c);
Tracking User Access Counts
(Continued)
out println(docType +
[Link](docType
"<HTML>\n" +
"<HEAD><TITLE>" + title +
"</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + title
titl + "</H1>\
"</H1>\n"
" +
"<H2>This is visit number " +
count + " by this browser.</H2>\n"+
"</CENTER></BODY></HTML>");
/
/
/
)
}
}
28
Tracking User Access Counts
(Results)
29
Using Cookies to Remember
User Preferences
RegistrationForm servlet
Uses cookie values to prepopulate form field values
Uses default values if no cookies are found
Will be redone in JSP later in class
Registration servlet
Creates cookies based on request parameters received
Displays values if all parameters are present
Redirects to form if any parameter is missing
30
RegistrationForm Servlet
@WebServlet("/registration-form")
public class RegistrationForm
p
g
extends HttpServlet
p
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response setContentType("text/html");
[Link]("text/html");
PrintWriter out = [Link]();
String firstName =
[Link](request,
"firstName", "");
String lastName =
[Link](request,
lastName , "");
);
"lastName"
String emailAddress =
[Link](request,
"emailAddress",
"");
31
RegistrationForm Servlet
(Continued)
32
[Link]
(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + title + "</H1>\n" +
"<FORM ACTION=\"registration\">\n" +
"First Name:\n" +
" <INPUT TYPE=\"TEXT\"
TYPE \ TEXT\ NAME
NAME=\"firstName\"
\ firstName\ " +
"VALUE=\"" + firstName + "\"><BR>\n" +
"Last Name:\n" +
" <INPUT TYPE=\"TEXT\" NAME=\"lastName\" " +
"VALUE=\""
VALUE=\
+ lastName + "\"><BR>\n"+
\ ><BR>\n +
"Email Address: \n" +
" <INPUT TYPE=\"TEXT\" NAME=\"emailAddress\" " +
"VALUE=\"" + emailAddress + "\"><P>\n" +
"<INPUT
<INPUT TYPE=\"SUBMIT\"
TYPE=\ SUBMIT\ VALUE=\
VALUE=\"Register\">\n"
Register\ >\n +
"</FORM></CENTER></BODY></HTML>");
Registration Servlet
33
@WebServlet("/registration")
public class RegistrationServlet
p
g
extends HttpServlet
p
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response setContentType("text/html");
[Link]("text/html");
boolean isMissingValue = false;
String firstName =
[Link]("firstName");
if (isMissing(firstName)) {
firstName = "Missing first name";
isMissingValue = true;
}
String lastName =
[Link]("lastName");
if (isMissing(lastName)) {
lastName = "Missing last name";
isMissingValue = true;
}
Registration Servlet (Continued)
Cookie c1 =
new LongLivedCookie(
LongLivedCookie("firstName"
firstName , firstName);
[Link](c1);
Cookie c2 =
new LongLivedCookie("lastName",
LongLivedCookie("lastName" lastName);
[Link](c2);
Cookie c3 = new LongLivedCookie("emailAddress",
emailAddress);
ilAdd
)
[Link](c3);
if (isMissingValue) {
[Link]("registration-form");
(
)
} else { }
34
RegistrationForm (Initial Result)
35
RegistrationForm
(Submitting Incomplete Form)
36
RegistrationForm
(Submitting Complete Form)
37
RegistrationForm
(Initial Result on Later Visit)
38
Summary
Basic functionality
C
Cookies
ki involve
i
l name/value
/ l pairs
i sentt from
f
server to
t
browser and automatically returned when the same page
(or possibly same site or domain) is visited later
Cookies
C ki llett you
Track sessions (use higher-level session-tracking API)
Permit users to avoid logging in at low-security
low security sites
Customize sites for different users
Focus content or advertising
Setting cookies
Call Cookie constructor, set age, call [Link]
Reading cookies
39
Call [Link], check for null, look through
array for matching name, use associated value
2010 Marty Hall
Questions?
Customized Java EE Training: [Link]
40
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.