SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
© 2010 Marty Hall
H dli C kiHandling Cookies
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
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.2
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
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.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Agenda
• Understanding the benefits and drawbacks
f kiof cookies
• Sending outgoing cookies
R i i i i ki• Receiving incoming cookies
• Tracking repeat visitors
S if i ki tt ib t• Specifying cookie attributes
• Differentiating between session cookies and
persistent cookiespersistent cookies
• Simplifying cookie usage with utility classes
• Modifying cookie values• 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 depending on cookiesame site (or same domain, depending on cookie
settings).
• Typical Uses of Cookiesyp
– Identifying a user during an e-commerce session
• Servlets have a higher-level API for this task
Avoiding username and password– Avoiding username and password
– Customizing a site
– Focusing advertisingg g
5
Cookies and Focused
AdvertisingAdvertising
6
Cookies and Privacy
FoxTrot © 1998 Bill Amend Reprinted with permission ofFoxTrot © 1998 Bill Amend. Reprinted with permission of
Universal Press Syndicate. All rights reserved.
7
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 actionsinformation to your previous actions
– Servers can share cookie information through use of a
cooperating third party like doubleclick.net
– Poorly designed sites store sensitive information like credit
card numbers directly in cookie
– JavaScript bugs let hostile sites steal cookies (old browsers)– JavaScript bugs let hostile sites steal cookies (old browsers)
• Moral for servlet authors
– If cookies are not critical to your task, avoid servlets thatcoo es a e ot c t ca to you tas , avo d se v ets t at
totally fail when cookies are disabled
– Don’t put sensitive info in cookies8
Manually Deleting Cookies
(To Simplify Testing)(To Simplify Testing)
9
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");Cookie c = new Cookie( userID , a1234 );
• Set the maximum age.
– To tell browser to store cookie on disk instead of just in– 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);
10
Reading Cookies from the Client
• Call request.getCookies
This yields an array of Cookie objects– This yields an array of Cookie objects.
• Loop down the array, calling getName on each
entry until you find the cookie of interest
U th l ( tV l ) i li ti ifi– Use the value (getValue) in application-specific way.
String cookieName = "userID";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(Cookie cookie: cookies) {o (Coo e coo e: coo es) {
if (cookieName.equals(cookie.getName())) {
doSomethingWith(cookie.getValue());
}}
}
}
11
Using Cookies to Detect
First-Time VisitorsFirst-Time Visitors
public class RepeatVisitor extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
boolean newbie = true;boolean newbie = true;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
f (C ki ki ) {for(Cookie c: cookies) {
if ((c.getName().equals("repeatVisitor")) &&
(c.getValue().equals("yes"))) {
newbie = false;
break;
}
}
}
12
Using Cookies to Detect
First-Time Visitors (Continued)First-Time Visitors (Continued)
String title;
if (newbie) {if (newbie) {
Cookie returnVisitorCookie =
new Cookie("repeatVisitor", "yes");
returnVisitorCookie setMaxAge(60*60*24*365);returnVisitorCookie.setMaxAge(60*60*24*365);
response.addCookie(returnVisitorCookie);
title = "Welcome Aboard";
} l {} else {
title = "Welcome Back";
}
( / )response.setContentType("text/html");
PrintWriter out = response.getWriter();
… // (Output page with above title)
13
Using Cookies to Detect
First-Time Visitors (Results)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• getMaxAge/setMaxAge
– Gets/sets the cookie expiration time (in seconds). If you
fail to set this, cookie applies to current browsing session
l S L Li dC ki h l l i lionly. See LongLivedCookie helper class given earlier.
• getName
Gets the cookie name There is no setName method; you– Gets the cookie 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
containing current page.g p g
• getSecure/setSecure
– Gets/sets flag indicating whether cookie should apply
l t SSL ti t ll tionly to SSL connections or to all connections.
• getValue/setValue
Gets/sets value associated with cookie For new cookies– 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 youcookie 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.16
Differentiating Session Cookies
from Persistent Cookiesfrom Persistent Cookies
public class CookieTest extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
for(int i=0; i<3; i++) {for(int i=0; i<3; i++) {
Cookie cookie =
new Cookie("Session-Cookie-" + i,
"C ki V l S" + i)"Cookie-Value-S" + i);
// No maxAge (ie maxAge = -1)
response.addCookie(cookie);
(cookie = new Cookie("Persistent-Cookie-" + i,
"Cookie-Value-P" + i);
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
17
Differentiating Session Cookies
from Persistent Cookies (Cont)from Persistent Cookies (Cont)
… // Start an HTML table
Cookie[] cookies = request getCookies();Cookie[] cookies = request.getCookies();
if (cookies == null) {
out.println("<TR><TH COLSPAN=2>No cookies");
} else {} else {
for(Cookie cookie: cookies) {
out.println
("<TR> " +("<TR>n" +
" <TD>" + cookie.getName() + "n" +
" <TD>" + cookie.getValue());
}
}
out.println("</TABLE></BODY></HTML>");
}
}
18
Differentiating Session Cookies
from Persistent Cookiesfrom 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 Cookiesfrom Persistent Cookies
• Result of revisiting CookieTest within an hour
f i i l i it ( b i )of original visit (same browser session)
– I.e., browser stayed open between the original visit and
the visit shown herethe visit shown here
20
Differentiating Session Cookies
from Persistent Cookiesfrom Persistent Cookies
• Result of revisiting CookieTest within an hour
f i i l i it (diff t b i )of original visit (different browser session)
– I.e., browser was restarted between the original visit and
the visit shown herethe visit shown here.
21
Utility: Finding Cookies with
Specified NamesSpecified Names
public class CookieUtilities {
public static String getCookieValuepublic static String getCookieValue
(HttpServletRequest request,
String cookieName,
String defaultValue) {g ) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(Cookie cookie: cookies) {
if (cookieName.equals(cookie.getName())) {
return(cookie.getValue());
}
}}
}
return(defaultValue);
}}
…
}
22
Utility: Creating Long-Lived
CookiesCookies
public class LongLivedCookie extends Cookie {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:
RepeatVisitor2RepeatVisitor2
public class RepeatVisitor2 extends HttpServlet {
public void doGet(HttpServletRequest request,p p q q
HttpServletResponse response)
throws ServletException, IOException {
boolean newbie = true;
String value =String value
CookieUtilities.getCookieValue(request,
"repeatVisitor2",
"no");
if (value equals("yes")) {if (value.equals("yes")) {
newbie = false;
}
String title;
if ( bi ) {if (newbie) {
LongLivedCookie returnVisitorCookie =
new LongLivedCookie("repeatVisitor2", "yes");
response.addCookie(returnVisitorCookie);
title = "Welcome Aboard";
} else {
title = "Welcome Back";
}24
Modifying Cookie Values
• Replacing a cookie value
– Send the same cookie name with a different cookie value.
– Reusing incoming Cookie objects.
• Need to call response addCookie; merely calling setValue• Need to call response.addCookie; merely calling setValue
is not sufficient.
• Also need to reapply any relevant cookie attributes by
calling setMaxAge setPath etc —cookie attributes are notcalling setMaxAge, setPath, etc.—cookie attributes are not
specified for incoming cookies.
• Usually not worth the bother, so new Cookie object used
Instructing the browser to delete a cookie• Instructing the browser to delete a cookie
– Use setMaxAge to assign a maximum age of 0.
25
Tracking User Access Counts
public class ClientAccessCounts extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String countString =String countString =
CookieUtilities.getCookieValue(request,
"accessCount",
"1");1 );
int count = 1;
try {
count = Integer.parseInt(countString);cou t tege .pa se t(cou tSt g);
} catch(NumberFormatException nfe) { }
LongLivedCookie c =
new LongLivedCookie("accessCount",g ( ,
String.valueOf(count+1));
response.addCookie(c);
26
Tracking User Access Counts
(Continued)(Continued)
…
out println(docType +out.println(docType +
"<HTML>n" +
"<HEAD><TITLE>" + title +
"</TITLE></HEAD>n" +"</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<CENTER>n" +
"<H1>" + titl + "</H1> " +"<H1>" + title + "</H1>n" +
"<H2>This is visit number " +
count + " by this browser.</H2>n"+
/ / / )"</CENTER></BODY></HTML>");
}
}
27
Tracking User Access Counts
(Results)(Results)
28
Using Cookies to Remember
User PreferencesUser 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– Will be redone in JSP later in class
• Registration servletRegistration servlet
– Creates cookies based on request parameters received
– Displays values if all parameters are present
– Redirects to form if any parameter is missing
29
RegistrationForm Servlet
public class RegistrationForm extends HttpServlet {
public void doGet(HttpServletRequest request,p ( p q q ,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response getWriter();PrintWriter out = response.getWriter();
String actionURL =
"coreservlets.RegistrationServlet";
String firstName =
CookieUtilities.getCookieValue(request,
"firstName", "");
String lastName =
CookieUtilities getCookieValue(requestCookieUtilities.getCookieValue(request,
"lastName", "");
String emailAddress =
CookieUtilities.getCookieValue(request,
"emailAddress",
"");
30
RegistrationForm Servlet
(Continued)(Continued)
out.println
(docType +
"<HTML>n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<CENTER>n" +
"<H1>" + title + "</H1>n" +
"<FORM ACTION="" + actionURL + "">n" +
"First Name:n" +
" <INPUT TYPE="TEXT" NAME="firstName" " +
"VALUE="" + firstName + ""><BR>n" +
"Last Name:n" +
" <INPUT TYPE="TEXT" NAME="lastName" " +
"VALUE="" + lastName + ""><BR>n"+
"Email Address: n" +
" <INPUT TYPE="TEXT" NAME="emailAddress" " +
"VALUE="" + emailAddress + ""><P>n" +
"<INPUT TYPE="SUBMIT" VALUE="Register">n" +g
"</FORM></CENTER></BODY></HTML>");
}
}
31
Registration Servlet
public class RegistrationServlet extends HttpServlet {
public void doGet(HttpServletRequest request,p ( p q q ,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
boolean isMissingValue = false;boolean isMissingValue = false;
String firstName =
request.getParameter("firstName");
if (isMissing(firstName)) {
firstName = "Missing first name";
isMissingValue = true;
}
String lastName =String lastName =
request.getParameter("lastName");
if (isMissing(lastName)) {
lastName = "Missing last name";
isMissingValue = true;
}
…
32
Registration Servlet (Continued)
Cookie c1 =
new LongLivedCookie("firstName" firstName);new LongLivedCookie( firstName , firstName);
response.addCookie(c1);
Cookie c2 =
new LongLivedCookie("lastName" lastName);new LongLivedCookie("lastName", lastName);
response.addCookie(c2);
Cookie c3 = new LongLivedCookie("emailAddress",
ilAdd )emailAddress);
response.addCookie(c3);
String formAddress =
"coreservlets.RegistrationForm";
if (isMissingValue) {
response.sendRedirect(formAddress);
} else { … }
33
RegistrationForm (Initial Result)
34
RegistrationForm (Submitting
Incomplete Form)Incomplete Form)
35
RegistrationForm (Submitting
Complete Form)Complete Form)
36
RegistrationForm
(Initial Result on Later Visit)(Initial Result on Later Visit)
37
Summary
• Basic functionality
C ki i l / l i t f t– Cookies involve name/value pairs sent from server to
browser and automatically returned when the same page,
site, or domain is visited later
• Let you• Let you
– Track sessions (use higher-level session-tracking API)
– Permit users to avoid logging in at low-security sitesgg g y
– Customize sites for different users
– Focus content or advertising
• Setting cookies• Setting cookies
– Call Cookie constructor, set age, call response.addCookie
• Reading cookiesg
– Call request.getCookies, check for null, look through
array for matching name, use associated value
38
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
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.39

Weitere ähnliche Inhalte

Ähnlich wie 07 cookies

javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptxMattMarino13
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
Advance java session 7
Advance java session 7Advance java session 7
Advance java session 7Smita B Kumar
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptxVatsalJain39
 
Morphing GA into an Affiliate Analytics Monster
Morphing GA into an Affiliate Analytics MonsterMorphing GA into an Affiliate Analytics Monster
Morphing GA into an Affiliate Analytics MonsterPhil Pearce
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSDegu8
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionMazenetsolution
 
Cookies in php lecture 2
Cookies in php  lecture  2Cookies in php  lecture  2
Cookies in php lecture 2Mudasir Syed
 
Cookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServiceCookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServicePradeep Kumar
 
Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erickokelloerick
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NETShingalaKrupa
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servletsvishal choudhary
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptxssuser4a97d3
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Hassen Poreya
 

Ähnlich wie 07 cookies (20)

javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
 
Ecom2
Ecom2Ecom2
Ecom2
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
Advance java session 7
Advance java session 7Advance java session 7
Advance java session 7
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx
 
Morphing GA into an Affiliate Analytics Monster
Morphing GA into an Affiliate Analytics MonsterMorphing GA into an Affiliate Analytics Monster
Morphing GA into an Affiliate Analytics Monster
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
ASP.NET-Web Programming - Sessions and Cookies
ASP.NET-Web Programming - Sessions and CookiesASP.NET-Web Programming - Sessions and Cookies
ASP.NET-Web Programming - Sessions and Cookies
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Cookies in php lecture 2
Cookies in php  lecture  2Cookies in php  lecture  2
Cookies in php lecture 2
 
Cookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServiceCookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesService
 
Lecture8 php page control by okello erick
Lecture8 php page control by okello erickLecture8 php page control by okello erick
Lecture8 php page control by okello erick
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
 

Mehr von snopteck

13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
01 web-apps
01 web-apps01 web-apps
01 web-appssnopteck
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 

Mehr von snopteck (10)

10 jdbc
10 jdbc10 jdbc
10 jdbc
 
14 mvc
14 mvc14 mvc
14 mvc
 
13 java beans
13 java beans13 java beans
13 java beans
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
01 web-apps
01 web-apps01 web-apps
01 web-apps
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 

Kürzlich hochgeladen

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Kürzlich hochgeladen (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

07 cookies

  • 1. © 2010 Marty Hall H dli C kiHandling Cookies Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ 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.2 © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ 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. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Agenda • Understanding the benefits and drawbacks f kiof cookies • Sending outgoing cookies R i i i i ki• Receiving incoming cookies • Tracking repeat visitors S if i ki tt ib t• Specifying cookie attributes • Differentiating between session cookies and persistent cookiespersistent cookies • Simplifying cookie usage with utility classes • Modifying cookie values• 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 depending on cookiesame site (or same domain, depending on cookie settings). • Typical Uses of Cookiesyp – Identifying a user during an e-commerce session • Servlets have a higher-level API for this task Avoiding username and password– Avoiding username and password – Customizing a site – Focusing advertisingg g 5
  • 3. Cookies and Focused AdvertisingAdvertising 6 Cookies and Privacy FoxTrot © 1998 Bill Amend Reprinted with permission ofFoxTrot © 1998 Bill Amend. Reprinted with permission of Universal Press Syndicate. All rights reserved. 7
  • 4. 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 actionsinformation to your previous actions – Servers can share cookie information through use of a cooperating third party like doubleclick.net – Poorly designed sites store sensitive information like credit card numbers directly in cookie – JavaScript bugs let hostile sites steal cookies (old browsers)– JavaScript bugs let hostile sites steal cookies (old browsers) • Moral for servlet authors – If cookies are not critical to your task, avoid servlets thatcoo es a e ot c t ca to you tas , avo d se v ets t at totally fail when cookies are disabled – Don’t put sensitive info in cookies8 Manually Deleting Cookies (To Simplify Testing)(To Simplify Testing) 9
  • 5. 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");Cookie c = new Cookie( userID , a1234 ); • Set the maximum age. – To tell browser to store cookie on disk instead of just in– 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); 10 Reading Cookies from the Client • Call request.getCookies This yields an array of Cookie objects– This yields an array of Cookie objects. • Loop down the array, calling getName on each entry until you find the cookie of interest U th l ( tV l ) i li ti ifi– Use the value (getValue) in application-specific way. String cookieName = "userID"; Cookie[] cookies = request.getCookies(); if (cookies != null) { for(Cookie cookie: cookies) {o (Coo e coo e: coo es) { if (cookieName.equals(cookie.getName())) { doSomethingWith(cookie.getValue()); }} } } 11
  • 6. Using Cookies to Detect First-Time VisitorsFirst-Time Visitors public class RepeatVisitor extends HttpServlet { public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean newbie = true;boolean newbie = true; Cookie[] cookies = request.getCookies(); if (cookies != null) { f (C ki ki ) {for(Cookie c: cookies) { if ((c.getName().equals("repeatVisitor")) && (c.getValue().equals("yes"))) { newbie = false; break; } } } 12 Using Cookies to Detect First-Time Visitors (Continued)First-Time Visitors (Continued) String title; if (newbie) {if (newbie) { Cookie returnVisitorCookie = new Cookie("repeatVisitor", "yes"); returnVisitorCookie setMaxAge(60*60*24*365);returnVisitorCookie.setMaxAge(60*60*24*365); response.addCookie(returnVisitorCookie); title = "Welcome Aboard"; } l {} else { title = "Welcome Back"; } ( / )response.setContentType("text/html"); PrintWriter out = response.getWriter(); … // (Output page with above title) 13
  • 7. Using Cookies to Detect First-Time Visitors (Results)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• getMaxAge/setMaxAge – Gets/sets the cookie expiration time (in seconds). If you fail to set this, cookie applies to current browsing session l S L Li dC ki h l l i lionly. See LongLivedCookie helper class given earlier. • getName Gets the cookie name There is no setName method; you– Gets the cookie 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
  • 8. 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 containing current page.g p g • getSecure/setSecure – Gets/sets flag indicating whether cookie should apply l t SSL ti t ll tionly to SSL connections or to all connections. • getValue/setValue Gets/sets value associated with cookie For new cookies– 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 youcookie 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.16 Differentiating Session Cookies from Persistent Cookiesfrom Persistent Cookies public class CookieTest extends HttpServlet { public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) {for(int i=0; i<3; i++) { Cookie cookie = new Cookie("Session-Cookie-" + i, "C ki V l S" + i)"Cookie-Value-S" + i); // No maxAge (ie maxAge = -1) response.addCookie(cookie); (cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); cookie.setMaxAge(3600); response.addCookie(cookie); } 17
  • 9. Differentiating Session Cookies from Persistent Cookies (Cont)from Persistent Cookies (Cont) … // Start an HTML table Cookie[] cookies = request getCookies();Cookie[] cookies = request.getCookies(); if (cookies == null) { out.println("<TR><TH COLSPAN=2>No cookies"); } else {} else { for(Cookie cookie: cookies) { out.println ("<TR> " +("<TR>n" + " <TD>" + cookie.getName() + "n" + " <TD>" + cookie.getValue()); } } out.println("</TABLE></BODY></HTML>"); } } 18 Differentiating Session Cookies from Persistent Cookiesfrom 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
  • 10. Differentiating Session Cookies from Persistent Cookiesfrom Persistent Cookies • Result of revisiting CookieTest within an hour f i i l i it ( b i )of original visit (same browser session) – I.e., browser stayed open between the original visit and the visit shown herethe visit shown here 20 Differentiating Session Cookies from Persistent Cookiesfrom Persistent Cookies • Result of revisiting CookieTest within an hour f i i l i it (diff t b i )of original visit (different browser session) – I.e., browser was restarted between the original visit and the visit shown herethe visit shown here. 21
  • 11. Utility: Finding Cookies with Specified NamesSpecified Names public class CookieUtilities { public static String getCookieValuepublic static String getCookieValue (HttpServletRequest request, String cookieName, String defaultValue) {g ) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for(Cookie cookie: cookies) { if (cookieName.equals(cookie.getName())) { return(cookie.getValue()); } }} } return(defaultValue); }} … } 22 Utility: Creating Long-Lived CookiesCookies public class LongLivedCookie extends Cookie {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
  • 12. Applying Utilities: RepeatVisitor2RepeatVisitor2 public class RepeatVisitor2 extends HttpServlet { public void doGet(HttpServletRequest request,p p q q HttpServletResponse response) throws ServletException, IOException { boolean newbie = true; String value =String value CookieUtilities.getCookieValue(request, "repeatVisitor2", "no"); if (value equals("yes")) {if (value.equals("yes")) { newbie = false; } String title; if ( bi ) {if (newbie) { LongLivedCookie returnVisitorCookie = new LongLivedCookie("repeatVisitor2", "yes"); response.addCookie(returnVisitorCookie); title = "Welcome Aboard"; } else { title = "Welcome Back"; }24 Modifying Cookie Values • Replacing a cookie value – Send the same cookie name with a different cookie value. – Reusing incoming Cookie objects. • Need to call response addCookie; merely calling setValue• Need to call response.addCookie; merely calling setValue is not sufficient. • Also need to reapply any relevant cookie attributes by calling setMaxAge setPath etc —cookie attributes are notcalling setMaxAge, setPath, etc.—cookie attributes are not specified for incoming cookies. • Usually not worth the bother, so new Cookie object used Instructing the browser to delete a cookie• Instructing the browser to delete a cookie – Use setMaxAge to assign a maximum age of 0. 25
  • 13. Tracking User Access Counts public class ClientAccessCounts extends HttpServlet { public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String countString =String countString = CookieUtilities.getCookieValue(request, "accessCount", "1");1 ); int count = 1; try { count = Integer.parseInt(countString);cou t tege .pa se t(cou tSt g); } catch(NumberFormatException nfe) { } LongLivedCookie c = new LongLivedCookie("accessCount",g ( , String.valueOf(count+1)); response.addCookie(c); 26 Tracking User Access Counts (Continued)(Continued) … out println(docType +out.println(docType + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +"</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<CENTER>n" + "<H1>" + titl + "</H1> " +"<H1>" + title + "</H1>n" + "<H2>This is visit number " + count + " by this browser.</H2>n"+ / / / )"</CENTER></BODY></HTML>"); } } 27
  • 14. Tracking User Access Counts (Results)(Results) 28 Using Cookies to Remember User PreferencesUser 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– Will be redone in JSP later in class • Registration servletRegistration servlet – Creates cookies based on request parameters received – Displays values if all parameters are present – Redirects to form if any parameter is missing 29
  • 15. RegistrationForm Servlet public class RegistrationForm extends HttpServlet { public void doGet(HttpServletRequest request,p ( p q q , HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response getWriter();PrintWriter out = response.getWriter(); String actionURL = "coreservlets.RegistrationServlet"; String firstName = CookieUtilities.getCookieValue(request, "firstName", ""); String lastName = CookieUtilities getCookieValue(requestCookieUtilities.getCookieValue(request, "lastName", ""); String emailAddress = CookieUtilities.getCookieValue(request, "emailAddress", ""); 30 RegistrationForm Servlet (Continued)(Continued) out.println (docType + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<CENTER>n" + "<H1>" + title + "</H1>n" + "<FORM ACTION="" + actionURL + "">n" + "First Name:n" + " <INPUT TYPE="TEXT" NAME="firstName" " + "VALUE="" + firstName + ""><BR>n" + "Last Name:n" + " <INPUT TYPE="TEXT" NAME="lastName" " + "VALUE="" + lastName + ""><BR>n"+ "Email Address: n" + " <INPUT TYPE="TEXT" NAME="emailAddress" " + "VALUE="" + emailAddress + ""><P>n" + "<INPUT TYPE="SUBMIT" VALUE="Register">n" +g "</FORM></CENTER></BODY></HTML>"); } } 31
  • 16. Registration Servlet public class RegistrationServlet extends HttpServlet { public void doGet(HttpServletRequest request,p ( p q q , HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); boolean isMissingValue = false;boolean isMissingValue = false; String firstName = request.getParameter("firstName"); if (isMissing(firstName)) { firstName = "Missing first name"; isMissingValue = true; } String lastName =String lastName = request.getParameter("lastName"); if (isMissing(lastName)) { lastName = "Missing last name"; isMissingValue = true; } … 32 Registration Servlet (Continued) Cookie c1 = new LongLivedCookie("firstName" firstName);new LongLivedCookie( firstName , firstName); response.addCookie(c1); Cookie c2 = new LongLivedCookie("lastName" lastName);new LongLivedCookie("lastName", lastName); response.addCookie(c2); Cookie c3 = new LongLivedCookie("emailAddress", ilAdd )emailAddress); response.addCookie(c3); String formAddress = "coreservlets.RegistrationForm"; if (isMissingValue) { response.sendRedirect(formAddress); } else { … } 33
  • 17. RegistrationForm (Initial Result) 34 RegistrationForm (Submitting Incomplete Form)Incomplete Form) 35
  • 18. RegistrationForm (Submitting Complete Form)Complete Form) 36 RegistrationForm (Initial Result on Later Visit)(Initial Result on Later Visit) 37
  • 19. Summary • Basic functionality C ki i l / l i t f t– Cookies involve name/value pairs sent from server to browser and automatically returned when the same page, site, or domain is visited later • Let you• Let you – Track sessions (use higher-level session-tracking API) – Permit users to avoid logging in at low-security sitesgg g y – Customize sites for different users – Focus content or advertising • Setting cookies• Setting cookies – Call Cookie constructor, set age, call response.addCookie • Reading cookiesg – Call request.getCookies, check for null, look through array for matching name, use associated value 38 © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ 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.39