Presentation is loading. Please wait.

Presentation is loading. Please wait.

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,

Similar presentations


Presentation on theme: "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,"— Presentation transcript:

1 Cookies

2 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, the cookie is sent unchanged back to the server A cookie is a keyed piece of data that is created by the server and stored by the client browser. Browsers maintain their own list of unique cookies. This makes cookies a very viable solution for session The Servlet API provides built-in support for cookies. It does this through the use of the Cookie class and the HttpServletResponse.addCookie() and HttpServletRequest. getCookies() methods.

3 Cont.. The problem is privacy, not security. Don't put sensitive info in cookies Cookie definition: – Web server sends a cookie name and value to a browser and later can read them back from the browser. The process: – Servlet sends a cookie with its response to the client. – The client saves the cookie. – The client returns a cookie back with subsequent requests (depends on some rules).

4 Servlet API supports cookies: – javax.servlet.http.cookie Response.addCookie(Cookie) add cookies to a Response. Cookie cookie = new Cookie("name", "value"); response.addCookie(cookie); reuqest.getCookie() get cookie from a request. Cookie[] cookie =request.getCookie(); if (cookie != null) { for (int i= 0; i< cookie.length; i++) { String name = cookie[i].getName(); String value = cookie[i].getValue(); }

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

6 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()); }

7 Using Cookie Methods 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.

8 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

9 Advantages: – Very easy to implement. – Highly customizable. – Persist across browser shut-downs Disadvantages: – Often: users turn off cookies for privacy or security reason. – Not quite universal browser support.

10 Add Cookie.html <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servlet/AddCookieS ervlet"> Enter a value for MyCookie:

11 AddCookie Servelet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get parameter from HTTP request. String data = request.getParameter("data"); // Create cookie. Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response. response.addCookie(cookie);

12 // Write output to browser. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println(" MyCookie has been set to"); pw.println(data); pw.close(); }

13 <form name="Form1" method="post“ action="http://localhost:8080/examples/servlets/servlet/PostPa rametersServlet"> Employee Phone

14 . import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // print out cookies Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value); }

15 // set a cookie String name = request.getParameter("cookieName"); if (name != null && name.length() > 0) { String value = request.getParameter("cookieValue"); Cookie c = new Cookie(name, value); response.addCookie(c); }

16 Web.xml CookieExample CookieExample /servlets/servlet/CookieExample

17 Cookies Example Your browser is sending the following cookies: Cookie Name: venkat Cookie Value: 90 Create a cookie to send to your browser Name: Value: Submit Query Venkta Venkat

18 How Do We Need HTTP State? Web applications need to track the users across a series of requests: Online shopping (e.g. Order books). – Financial portfolio manager. – Movie listings. HTTP does not support directly. Need a mechanism to maintain state about a series of requests from the same user ( or originating from the same browser) over some period of time.

19 What is Session Tracking? HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. Number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. how does the server remember what you were buying?

20 A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings. It is important to note that session state is shared among all the servlets that are associated with a particular client

21 HTTP protocol  HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.stateless protocol  For example, when a web server is required to customize the content of a web page for a user, the web application may have to track the user's progress from page to page.web pageweb application  A common solution is the use of HTTP cookies. Other methods include server side sessions, hidden variables (when the current page contains a form), and URL-rewriting using URI-encoded parameters, e.g.,HTTP cookiesform Cookie URL Rewriting Hidden form fields.

22 HTTP session An HTTP session is a sequence of network request-response transactions. An HTTP client initiates a request by establishing a Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80;Transmission Control Protocolport An HTTP server listening on that port waits for a client's request message. Upon receiving the request, the server sends back a status line, such as "HTTP/1.1 200 OK", and a message of its own. The body of this message is typically the requested resource, although an error message or other information may also be returned Mehtods : GET, POST and HEAD, OPTIONS, PUT, DELETE, TRACE and CONNECT.

23 Some methods (for example, HEAD, GET, OPTIONS and TRACE) are defined as safe, which means they are intended only for information retrieval and should not change the state of the server. In other words, they should not have side effects, beyond relatively harmless effects such as logging, caching, the serving of banner advertisements or incrementing a web counterside effectslogging cachingbanner advertisementsweb counter POST, PUT and DELETE are intended for actions that may cause side effects either on the server, or external side effects such as financial trafinancial tra nsactions or transmission of email nsactionsemail HTTP Status code 1 1xx Informational 1 1xx Informational 2 2xx Success 2 2xx Success 3 3xx Redirection 3 3xx Redirection 4 4xx Client Error 4 4xx Client Error 5 5xx Server Error 5 5xx Server Error

24 Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity. A different timeout may be set by server admin. public void invalidate() – Expires the session and unbinds all objects with it. boolean session.isNew() – Determines if session is new to client (not page). long session.getCreationTime() – Returns time at which session was first created. long session.getLastAccessedTime() – Returns when the user last accessed the server. getMaxInactiveInterval, setMaxInactiveInterval – Gets or sets the amount of time, session should go without access before being invalidated

25 import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the HttpSession object. HttpSession hs = request.getSession(true); // Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print(" ");

26 // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + " "); } // Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } The getAttribute( ) method is called to obtain the object that is bound to the name “date”. That object is a Date object that encapsulates the date and time when this page was last accessed. A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name “date” to this object.

27 URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies. URL rewriting provides you with another session tracking alternative. URL rewriting is a method in which the requested URL is modified to include a session ID. There are several ways to perform URL rewriting. You are going to look at one method that is provided by the Servlet API

28 URLs can be rewritten or encoded to include session information. URL rewriting usually includes a session id. id can be sent as extra path information: – http://.../servlet/Rewritten/688 – Works well if no need for extra path info. id can be sent as an added parameter: – http://.../servlet/Rewritten?sessionid=688http://.../servlet/Rewritten?sessionid=688 Advantages: – Let user remain anonymous. – They are universally supported(most styles). Disadvantages: – Tedious to rewrite all URLs. – Only works for dynamically created documents.

29 URL Rewriting

30 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class URLRewritingServlet extends HttpServlet { //Initialize global variables public void init(ServletConfig config) throws ServletException { super.init(config); } //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" URL Rewriting "); out.println(" ");

31 // Encode a URL string with the session id appended to it. String url = response.encodeRedirectURL( "http://localhost:8000/servlet/checkout?sid=5748"); // Redirect the client to the new URL response.sendRedirect(url); out.println(" "); out.close(); }

32 Hidden Form Fields Hidden form fields are another way to support session tracking. Hidden form fields do not display in the browser, but can be sent back to the server by submit..........

33 Cont.. Fields can have identification (session id) or just some thing to remember (occupation). Servlet reads the fields using req.getParameter(). Advantages: – Universally supported. – Allow anonymous users Disadvantages: – Only works for a sequence of dynamically generated forms. – Breaks down with static documents, emailed documents, bookmarked documents. – No browser shutdowns.


Download ppt "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,"

Similar presentations


Ads by Google