Servlet Session I: Cookie API Road Map  Creating Cookies  Cookie Attributes  Reading Cookies  Example 1: Basic Counter  Example 2: Tracking Multiple.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
JSP and Servelets.
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Handling Cookies Vijayan Sugumaran Decision and Information Sciences Oakland University Parts of this presentation was provided by
Servlet Session Tracking. 2 Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information: Information.
1 CS6320 – Servlet Cookies L. Grewe 2 What is a cookie? Name-value bindings sent by a server to a web browser and then sent back unchanged by the browser.
Servlet Session Tracking II Session API All material and examples are from
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
ASHIMA KALRA.  INTRODUCTION TO JSP INTRODUCTION TO JSP  IMPLICIT OBJECTS IMPLICIT OBJECTS  COOKIES COOKIES.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Cookies Set a cookie – setcookie() Extract data from a cookie - $_COOKIE Augment user authentication script with a cookie.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Servlet Pertemuan 7 Matakuliah: Web Programming Tahun: 2009.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Chapter 8 Handling Cookies. Cookie Cookies are small bits of textual information that a Web server sends to a browser and that the browser later returns.
JavaScript, Fourth Edition
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Chapter 8 Cookies And Security JavaScript, Third Edition.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
Mark Dixon 1 03 – Passing Data between pages: Forms, Sessions, & Query Strings.
Chapter 6 Server-side Programming: Java Servlets
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Session Tracking Lec 31. Revisiting Session Tracking HTTP is a stateless protocol  Every request is considered independent of every other request Many.
S ERVLETS Cookies Handling 5-Dec-15. S ERVLETS - C OOKIES H ANDLING Cookies are text files stored on the client computer and they are kept for various.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling Cookies Core Servlets & JSP book: More.
Cookies. Cookie A cookie is a piece of textual information Send by the Web server to the client browser Every time the browser visits the Web site again,
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
Session Tracking Parts of this presentation was provided by SSE.
©SoftMooreSlide 1 Cookies. ©SoftMooreSlide 2 Cookies Basic idea –web application sends a simple name/value pair to the client –when the client connects.
1 Servlets – Part 2 Representation and Management of Data on the Web.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Chapter 6 Server-side Programming: Java Servlets
Sessions.
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
CNT 4714: Enterprise Computing Spring 2009
Pre-assessment Questions
Servlet Session Tracking: Session API
Presentation transcript:

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

 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  You rarely call setName() directly, as you specify the name in the cookie constructor.  getName() is useful for reading in cookies. public String getName(); public void setName (String name);

Domain Attributes public String getDomain (); public void setDomain(String domain);  Normally, the browser only returns cookies to the exact same host that sent them.  You can use setDomain() to instruct the browser to send cookies to other hosts within the same domain.

Domain Example  Example: Cookies sent from a servlet at bali.vacations.com would not be forwarded to mexico.vacations.com.  If you do want to the cookie to be accessible to both hosts, set the domain to the highest level:  cookie.setDomain (“.vacations.com”);  Note that you are always required to include at least two dots. Hence, you must specify.vacations.com, not just vacations.com

Cookie Age  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. public int getMaxAge (); public void setMaxAge (int lifetime);

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

Path  By default, the browser will only return a cookie to URLs in or below the directory that created the cookie. public String getPath(); public void setPath (String path);

Path Example  Example: If you create a cookie at then:  The browser will send the cookie back to  The browser will not send the cookie back to  If you want the cookie to be sent to all pages, set the path to /  Cookie.setPath (“/”);  Very common, widely used practice.

Security  If you set Secure to true, the browser will only return the cookie when connecting over an encrypted connection.  By default, cookies are set to non- secure. public int getSecure (); public void setSecure (boolean);

Comments  Comments: you can specify a cookie comment via the setComment() method. But, comments are only supported in Version 1 cookies.  Hence, no one really uses these methods… public int getComment (); public void Comment (String)

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

 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 –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)run example

Example 2: CookieTest.java  Illustrates the differences between session and persistent cookies.  Creates a total of six cookies:  Three are session cookies  Three are persistent cookies  Servlet also uses request.getCookies() to find all incoming cookies and display them.  Listing 8.2:

Differentiating Session Cookies from Persistent Cookies public class CookieTest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { Cookie cookie = new Cookie("Session-Cookie-" + 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); }

Differentiating Session Cookies from Persistent Cookies (Cont) … // Start an HTML table Cookie[] cookies = request.getCookies(); if (cookies == null) { out.println(" No cookies"); } else { Cookie cookie; for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println (" \n" + " " + cookie.getName() + "\n" + " " + cookie.getValue()); }

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.

Differentiating Session Cookies from Persistent Cookies (run)run Result of revisiting CookieTest within an hour of original visit (same browser session) I.e., browser stayed open between the original visit and the visit shown here

Example 3: CookieUtilities Utility class (from coreservlets package): - that simplifies the retrieval of a cookie value, given a cookie name. - if value is not set, it will be set to defaultvalue that you supply to the method.  You can use in all your programs that deals with cookie retrieval  It saves time because you do not have to repeat same steps and details every time you deal with cookie (hide details):  Retrieve all cookies array  go through loop to find name,value.  CookiesUtilities two Main static methods (details 8.3 in book)  getCookieValue (HttpServletRequest request, String cookieName, String defaultValue)  // given request object and cookie name and defaultvalue, getCookieValue method return  // a cookievalue with matching name, in no value found return  //“defaultvalue” supplied  getCookie (HttpServletRequest request, String cookieName)  // given request object and cookie name, getCookie method return a cookie with //matching name, in no name found return “null”… see details for this method (8.3 in book)

CookieUtilities: Finding Cookies with Specified Names public class CookieUtilities { // has two methods (details 8.3 in book) //Given the request, a name, a default value, this // method tries to find the value of the cookie with // the given name. // if no cookie matches the name, the designated // default value is returned public static String getCookieValue (HttpServletRequest request, String cookieName, String defaultValue) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for(int i=0; i<cookies.length; i++){ // loop through available cookie Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { return(cookie.getValue());// return value for match name } } // if no cookie match, return default value return(defaultValue); } }

Another helpful Utility (coreservlets package): LongLivedCookie (8.4 in book) // small class you can use instead of Cookie if you want to your //cookie to automatically bet set (persists) for one year rather //than be deleted when browser closes(session cookie by default) 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); }

Applying Utilities: RepeatVisitor2 example (8.4 in BOOK) produces same result as last example (8.2) but using utilities provided by coreservlets package to make it easier (run)run public class RepeatVisitor2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean newbie = true; // CookieUtilities.getCookieValue loops through available cookie and return // value for cookie name “ repeatVisitor2” which is “yes” // if no match rturn default “no” String value = CookieUtilities.getCookieValue(request, "repeatVisitor2", "no"); if (value.equals("yes")) { newbie = false; } String title; if (newbie) { //if new_cookie, create a new one and set to one year using LongLivedCookie LongLivedCookie returnVisitorCookie = new LongLivedCookie("repeatVisitor2", "yes"); response.addCookie(returnVisitorCookie); title = "Welcome Aboard"; } else { title = "Welcome Back"; }

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 is not sufficient. Also need to reapply any relevant cookie attributes by calling setMaxAge, setPath, etc.—cookie attributes are not specified for incoming cookies. Usually not worth the bother, so new Cookie object used To delete cookie: Instructing the browser to delete a cookie Use setMaxAge to assign a maximum age of 0.

Example : ClientAccessCount (8.6 in book) - display the number of hits for each user. - The value of the cookie will be the counter - change the value of cookie with each visit (increment )  A few weeks back, we created a simple Counter servlet that keeps track of the number of “hits”.  Now, we want to display the number of hits for each user.  This is relatively simple to do:  We just create a counter cookie  The value of the cookie will be the counter  Increment the counter with each visit  and increment the counter cookie at each visit.  Listing 8.6:

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 + " \n" + " " + title + " \n" + " " + title + " \n" + " This is visit number " + count + " by this browser. \n"+ " "); }

Tracking User Access Counts (Results) (run live)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 can use utilities provided with coreservlets to make process easier  CookieUtilities.getCookieValue  LongLivedCookie

Midterm Exam Midterm Wed MAR 2 (during class) Required readings All PowerPoint lectures posted on the website Core Servlets: Chapter 1, Chapter 2 (skip sections , 2.11) Chapter3 Chapter 4 (skip sections ), Chapter 5 (skip sections 5.4 and 5.6) Chapter 6, Chapter 7 (Skip Sections ) Chapter 8 Chapter 19 Questions: will be based on Core Servlets readings, lectures, examples and Homework

Midterm Exam (format) Questions: will be based or readings, lectures, examples and Homework Multiple choice (testing main concepts) 1 write complete servlet (30 pts) (similar to example and to homework: Generate and parse forms Read and write to file Get data from form, headers and cookies Keep persistent counts Use data structure and other manipulations similar to homework Your servlets will be graded based on syntax and does the code actually work, and comments and modularity Paragraph questions 3- 8 (find errors and why, etc..)