Slides © Marty Hall, book © Sun Microsystems Press 1 Handling Cookies Core Servlets & JSP book: More.

Slides:



Advertisements
Similar presentations
JSP and Servelets.
Advertisements

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.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
JSP Java Server Pages Reference:
Servlet Session I: Cookie API Road Map  Creating Cookies  Cookie Attributes  Reading Cookies  Example 1: Basic Counter  Example 2: Tracking Multiple.
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
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling the Client Request: HTTP Request Headers Core Servlets & JSP.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
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.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Comp2513 Java Servlets and Sessions Daniel L. Silver, Ph.D.
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.
Slides © Marty Hall, book © Sun Microsystems Press 1 Including Files & Applets in JSP Documents Core Servlets & JSP book:
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Slides © Marty Hall, book © Sun Microsystems Press 1 Generating the HTTP Response Core Servlets & JSP book:
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Mark Dixon 1 03 – Passing Data between pages: Forms, Sessions, & Query Strings.
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling the Client Request: Form Data Core Servlets & JSP book:
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.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
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.
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:
Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book:
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
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,
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:
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Java Servlets By: Tejashri Udavant..
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Chapter 6 Server-side Programming: Java Servlets
Sessions.
Servlet.
Client / Session Identification Cookies
Generating the Server Response: HTTP Status Codes
Servlets and Java Server Pages
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.
Web Search Interfaces.
Presentation transcript:

Slides © Marty Hall, book © Sun Microsystems Press 1 Handling Cookies Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com

Cookies2 Agenda The potential of cookies The problems with cookies Sending cookies to browser Reading cookies from browser Simple cookie-handling servlets Cookie utilities Methods in the Cookie API A customized search engine front end

Cookies3 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 Servlets have a higher-level API for this task –Avoiding username and password –Customizing a site –Focusing advertising

Cookies4 Cookies and Focused Advertising

Cookies5 Cookies and Privacy FoxTrot © 1998 Bill Amend. Reprinted with permission of Universal Press Syndicate. All rights reserved.

Cookies6 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 doubleclick.net –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 cookies are not critical to your task, avoid servlets that totally fail when cookies are disabled –Don't put sensitive info in cookies

Cookies7 Sending Cookies to Browser Standard approach: Cookie c = new Cookie("name", "value"); c.setMaxAge(...); // Means cookie persists on disk // Set other attributes. response.addCookie(c); Simplified approach: –Use LongLivedCookie class: 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); }

Cookies8 Reading Cookies from Browser Standard approach: Cookie[] cookies = request.getCookies(); if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("someName")) { doSomethingWith(c); break; } Simplified approach: –Extract cookie or cookie value from cookie array by using ServletUtilities.getCookieValue or ServletUtilities.getCookie

Cookies9 Simple Cookie-Setting Servlet public class SetCookies 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); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(...);

Cookies10 Result of Cookie-Setting Servlet

Cookies11 Simple Cookie-Viewing Servlet public class ShowCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Active Cookies"; out.println(ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " Cookie Name\n" + " Cookie Value");

Cookies12 Simple Cookie-Viewing Servlet (Continued) Cookie[] cookies = request.getCookies(); if (cookies != null) { Cookie cookie; for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println(" \n" + " " + cookie.getName() + "\n" + " " + cookie.getValue()); } out.println(" "); }

Cookies13 Result of Cookie-Viewer (Before & After Restarting Browser)

Cookies14 Cookie Utilities Problem –getCookies returns an array of cookies –You almost always only care about one particular cookie Solution –Static methods to Extract a cookie value given a cookie name (default value if no match) Extract a Cookie object given a cookie name (null if no match)

Cookies15 ServletUtilities.getCookieValue public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultVal) { if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie.getValue()); } return(defaultVal); }

Cookies16 ServletUtilities.getCookie public static Cookie getCookie(Cookie[] cookies, String cookieName) { if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie); } return(null); }

Cookies17 Methods in the Cookie API 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. See LongLivedCookie helper class given earlier. getName –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.

Cookies18 Methods in the Cookie API (Continued) 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. getSecure/setSecure –Gets/sets flag indicating whether cookie should apply only to SSL connections or to all connections. 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.

Cookies19 A Customized Search Engine Interface Front end remembers settings for search engine, search string, and hits per page –Front end uses cookies –Back end sets cookies –In real life, don't really show previous queries!

Cookies20 Front End to SearchEngines Servlet public class SearchEnginesFrontEnd extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies = request.getCookies(); String searchString = ServletUtilities.getCookieValue(cookies, "searchString", "Java Programming"); String numResults = ServletUtilities.getCookieValue(cookies, "numResults", "10"); String searchEngine = ServletUtilities.getCookieValue(cookies, "searchEngine", "google");

Cookies21 Front End to SearchEngines Servlet (Continued)... out.println (... "<FORM ACTION=\"/servlet/" + "coreservlets.CustomizedSearchEngines\">\n" + " \n" + "Search String:\n" + "<INPUT TYPE=\"TEXT\" NAME=\"searchString\"\n" + " VALUE=\"" + searchString + "\"> \n" + "Results to Show Per Page:\n" + "<INPUT TYPE=\"TEXT\" NAME=\"numResults\"\n" + " VALUE=" + numResults + " SIZE=3> \n" + "<INPUT TYPE=\"RADIO\" NAME=\"searchEngine\"\n" + " VALUE=\"google\"" + checked("google", searchEngine) + ">\n" +...);

Cookies22 Customized SearchEngines Servlet (Back End) public class CustomizedSearchEngines extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String searchString = request.getParameter("searchString"); if ((searchString == null) || (searchString.length() == 0)) { reportProblem(response, "Missing search string."); return; } Cookie searchStringCookie = new LongLivedCookie("searchString", searchString); response.addCookie(searchStringCookie);... }

Cookies23 Summary Cookies involve name/value pairs sent from server to browser and returned when the same page, site, or domain is visited later Let you –Track sessions (use higher-level API) –Permit users to avoid logging in at low-security sites –Customize sites for different users –Focus content or advertising Setting cookies –Call Cookie constructor, set age, call response.addCookie Reading cookies –Call request.getCookies, check for null, look through array for matching name, use associated value

Slides © Marty Hall, book © Sun Microsystems Press 24 Questions? Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com