J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.

Slides:



Advertisements
Similar presentations
JSP and Servelets.
Advertisements

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.
 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.
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
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
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.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
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.
J2EE training: 1 TODO Replace Netscape examples with Firefox. In later two sections also.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Servlet Pertemuan 7 Matakuliah: Web Programming Tahun: 2009.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Chapter 8 Cookies And Security JavaScript, Third Edition.
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.
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.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Java Servlets & Java Server Pages Lecture July 2013.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
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:
Java Servlets and Java Server Pages Norman White Stern School of Business.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
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
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.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
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.
Java Servlets By: Tejashri Udavant..
Chapter 6 Server-side Programming: Java Servlets
Sessions.
Client / Session Identification Cookies
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.
CNT 4714: Enterprise Computing Spring 2009
Presentation transcript:

J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting institutions –Slides not permitted for use in commercial training courses except when taught by coreservlets.com (see Slides can be modified however instructor desires Instructor can give PDF or hardcopy to students, but should protect the PowerPoint files –This slide is suppressed in Slide Show mode

JSP, Servlet, Struts, JSF & Java Training: J2EE Books from Sun Press: © 2005 Marty Hall 2 Handling Cookies

J2EE training: 3 Agenda Understanding the benefits and drawbacks of cookies Sending outgoing cookies Receiving incoming cookies Tracking repeat visitors Specifying cookie attributes Differentiating between session cookies and persistent cookies Simplifying cookie usage with utility classes Modifying cookie values Remembering user preferences

J2EE training: 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 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

J2EE training: 5 Cookies and Focused Advertising

J2EE training: 6 Cookies and Privacy FoxTrot © 1998 Bill Amend. Reprinted with permission of Universal Press Syndicate. All rights reserved.

J2EE training: 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 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

J2EE training: 8 Manually Deleting Cookies (To Simplify Testing)

J2EE training: 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"); 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);

J2EE training: 10 Reading Cookies from the Client Call request.getCookies –This yields an array of Cookie 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. String cookieName = "userID"; Cookie[] cookies = request.getCookies(); if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { doSomethingWith(cookie.getValue()); }

J2EE training: 11 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; }

J2EE training: 12 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)

J2EE training: 13 Using Cookies to Detect First-Time Visitors (Results)

J2EE training: 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. 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.

J2EE training: 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. 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.

J2EE training: 16 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); }

J2EE training: 17 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()); }

J2EE training: 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.

J2EE training: 19 Differentiating Session Cookies from Persistent Cookies 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

J2EE training: 20 Differentiating Session Cookies from Persistent Cookies Result of revisiting CookieTest within an hour of original visit (different browser session) –I.e., browser was restarted between the original visit and the visit shown here.

J2EE training: 21 Utility: Finding Cookies with Specified Names public class CookieUtilities { 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++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { return(cookie.getValue()); } return(defaultValue); } … }

J2EE training: 22 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); }

J2EE training: 23 Applying Utilities: RepeatVisitor2 public class RepeatVisitor2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean newbie = true; String value = CookieUtilities.getCookieValue(request, "repeatVisitor2", "no"); if (value.equals("yes")) { newbie = false; } String title; if (newbie) { LongLivedCookie returnVisitorCookie = new LongLivedCookie("repeatVisitor2", "yes"); response.addCookie(returnVisitorCookie); title = "Welcome Aboard"; } else { title = "Welcome Back"; }

J2EE training: 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 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 Instructing the browser to delete a cookie –Use setMaxAge to assign a maximum age of 0.

J2EE training: 25 Tracking User Access Counts public class ClientAccessCounts extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String countString = CookieUtilities.getCookieValue(request, "accessCount", "1"); int count = 1; try { count = Integer.parseInt(countString); } catch(NumberFormatException nfe) { } LongLivedCookie c = new LongLivedCookie("accessCount", String.valueOf(count+1)); response.addCookie(c);

J2EE training: 26 Tracking User Access Counts (Continued) … out.println(docType + " \n" + " " + title + " \n" + " " + title + " \n" + " This is visit number " + count + " by this browser. \n"+ " "); }

J2EE training: 27 Tracking User Access Counts (Results)

J2EE training: 28 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

J2EE training: 29 RegistrationForm Servlet public class RegistrationForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String actionURL = "/servlet/coreservlets.RegistrationServlet"; String firstName = CookieUtilities.getCookieValue(request, "firstName", ""); String lastName = CookieUtilities.getCookieValue(request, "lastName", ""); String Address = CookieUtilities.getCookieValue(request, " Address", "");

J2EE training: 30 RegistrationForm Servlet (Continued) out.println (docType + " \n" + " " + title + " \n" + " \n" + " " + title + " \n" + " \n" + "First Name:\n" + " <INPUT TYPE=\"TEXT\" NAME=\"firstName\" " + "VALUE=\"" + firstName + "\"> \n" + "Last Name:\n" + " <INPUT TYPE=\"TEXT\" NAME=\"lastName\" " + "VALUE=\"" + lastName + "\"> \n"+ " Address: \n" + " <INPUT TYPE=\"TEXT\" NAME=\" Address\" " + "VALUE=\"" + Address + "\"> \n" + " \n" + " "); }

J2EE training: 31 Registration Servlet public class RegistrationServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); boolean isMissingValue = false; String firstName = request.getParameter("firstName"); if (isMissing(firstName)) { firstName = "Missing first name"; isMissingValue = true; } String lastName = request.getParameter("lastName"); if (isMissing(lastName)) { lastName = "Missing last name"; isMissingValue = true; } …

J2EE training: 32 Registration Servlet (Continued) Cookie c1 = new LongLivedCookie("firstName", firstName); response.addCookie(c1); Cookie c2 = new LongLivedCookie("lastName", lastName); response.addCookie(c2); Cookie c3 = new LongLivedCookie(" Address", Address); response.addCookie(c3); String formAddress = "/servlet/coreservlets.RegistrationForm"; if (isMissingValue) { response.sendRedirect(formAddress); } else { … }

J2EE training: 33 RegistrationForm (Initial Result)

J2EE training: 34 RegistrationForm (Submitting Incomplete Form)

J2EE training: 35 RegistrationForm (Submitting Complete Form)

J2EE training: 36 RegistrationForm (Initial Result on Later Visit)

J2EE training: 37 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

JSP, Servlet, Struts, JSF & Java Training: J2EE Books from Sun Press: © 2005 Marty Hall 38 Questions?