Cookies Cookie n n n A cookie is

  • Slides: 33
Download presentation
Cookies

Cookies

Cookie n n n A cookie is a piece of textual information Send by

Cookie n n n 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 Http. Servlet. Response. add. Cookie() and Http. Servlet. Request. get. Cookies() methods.

Cont. . The problem is privacy, not security. • Don't put sensitive info in

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. n 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). n

Servlet API supports cookies: – javax. servlet. http. cookie Response. add. Cookie(Cookie) add cookies

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

Sending Cookies to the Client Create a Cookie object. – Call the Cookie constructor

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("user. ID", "a 1234"); • Set the maximum age. – To tell browser to store cookie on disk instead of just in memory, use set. Max. Age (argument is in seconds) c. set. Max. Age(60*60*24*7); // One week • Place the Cookie into the HTTP response – Use response. add. Cookie. – If you forget this step, no cookie is sent to the browser! response. add. Cookie(c);

Reading Cookies from the Client n n Call request. get. Cookies – This yields

Reading Cookies from the Client n n Call request. get. Cookies – This yields an array of Cookie objects. • Loop down the array, calling get. Name on each entry until you find the cookie of interest – Use the value (get. Value) in application-specific way. String cookie. Name = "user. ID"; Cookie[] cookies = request. get. Cookies(); if (cookies != null) { for(int i=0; i<cookies. length; i++) { Cookie cookie = cookies[i]; if (cookie. Name. equals(cookie. get. Name())) { do. Something. With(cookie. get. Value()); } }

Using Cookie Methods get. Domain/set. Domain – Lets you specify domain to which cookie

Using Cookie Methods get. Domain/set. Domain – Lets you specify domain to which cookie applies. Current host must be part of domain specified. • get. Max. Age/set. Max. Age – Gets/sets the cookie expiration time (in seconds). If you fail to set this, cookie applies to current browsing session only. See Long. Lived. Cookie helper class given earlier. • get. Name – Gets the cookie name. There is no set. Name method; you supply name to constructor. For incoming cookie array, you use get. Name to find the cookie of interest.

get. Path/set. Path – Gets/sets the path to which cookie applies. If unspecified, cookie

get. Path/set. Path – Gets/sets the path to which cookie applies. If unspecified, cookie applies to URLs that are within or below directory containing current page. • get. Secure/set. Secure – Gets/sets flag indicating whether cookie should apply only to SSL connections or to all connections. • get. Value/set. Value – Gets/sets value associated with cookie. For new cookies, you supply value to constructor, not to set. Value. For incoming cookie array, you use get. Name to find the cookie of interest, then call get. Value on the result. If you set the value of an incoming cookie, you still have to send it back out with response. add. Cookie

Advantages: – Very easy to implement. – Highly customizable. – Persist across browser shut-downs

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.

Add Cookie. html <html> <body> <center> <form name="Form 1" method="post" action="http: //localhost: 8080/examples/servlet/Add. Cookie.

Add Cookie. html <html> <body> <center> <form name="Form 1" method="post" action="http: //localhost: 8080/examples/servlet/Add. Cookie. Ser vlet"> <B>Enter a value for My. Cookie: </B> <input type=textbox name="data" size=25 value=""> <input type=submit value="Submit"> </form> </body> </html>

Add. Cookie Servelet. java import java. io. *; import javax. servlet. http. *; public

Add. Cookie Servelet. java import java. io. *; import javax. servlet. http. *; public class Add. Cookie. Servlet extends Http. Servlet { public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { // Get parameter from HTTP request. String data = request. get. Parameter("data"); // Create cookie. Cookie cookie = new Cookie("My. Cookie", data); // Add cookie to HTTP response. add. Cookie(cookie); n n

// Write output to browser. response. set. Content. Type("text/html"); Print. Writer pw = response.

// Write output to browser. response. set. Content. Type("text/html"); Print. Writer pw = response. get. Writer(); pw. println("<B>My. Cookie has been set to"); pw. println(data); pw. close(); } }

<html> <body> <center> <form name="Form 1" method="post“ action="http: //localhost: 8080/examples/servlet/Post. Pa rameters. Servlet"> <table>

<html> <body> <center> <form name="Form 1" method="post“ action="http: //localhost: 8080/examples/servlet/Post. Pa rameters. Servlet"> <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr> </table> <input type=submit value="Submit"> </body> </html>

n . import java. io. *; import javax. servlet. http. *; public class Cookie.

n . import java. io. *; import javax. servlet. http. *; public class Cookie. Example extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); // print out cookies Cookie[] cookies = request. get. Cookies(); for (int i = 0; i < cookies. length; i++) { Cookie c = cookies[i]; String name = c. get. Name(); String value = c. get. Value(); out. println(name + " = " + value); }

// set a cookie String name = request. get. Parameter("cookie. Name"); if (name !=

// set a cookie String name = request. get. Parameter("cookie. Name"); if (name != null && name. length() > 0) { String value = request. get. Parameter("cookie. Value"); Cookie c = new Cookie(name, value); response. add. Cookie(c); } } }

Web. xml <servlet> <servlet-name>Cookie. Example</servlet-name> <servlet-class>Cookie. Example</servlet-class> </servlet> <servlet-mapping> <servlet-name>Cookie. Example</servlet-name> <urlpattern>/servlets/servlet/Cookie. Example</url-pattern> </servlet-mapping>

Web. xml <servlet> <servlet-name>Cookie. Example</servlet-name> <servlet-class>Cookie. Example</servlet-class> </servlet> <servlet-mapping> <servlet-name>Cookie. Example</servlet-name> <urlpattern>/servlets/servlet/Cookie. Example</url-pattern> </servlet-mapping>

Cookies Example n Your browser is sending the following cookies: Cookie Name: venkat Cookie

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

How Do We Need HTTP State? Web applications need to track the users across

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. n HTTP does not support directly. n 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.

What is Session Tracking? n n n HTTP is a stateless protocol. Each request

What is Session Tracking? n n n 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?

n A session can be created via the get. Session( ) method of Http.

n A session can be created via the get. Session( ) method of Http. Servlet. Request. An Http. Session object is returned. This object can store a set of bindings that associate names with objects. n The set. Attribute( ), get. Attribute. Names( ), and remove. Attribute( ) methods of Http. Session manage these bindings. n It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol Ø Ø Ø HTTP is a stateless protocol. A stateless protocol does

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. 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. 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. , Cookie URL Rewriting Hidden form fields.

HTTP session n n n n An HTTP session is a sequence of network

HTTP session n n n n 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; 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.

n Some methods (for example, HEAD, GET, OPTIONS and TRACE) are defined as safe,

n 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 counter n POST, PUT and DELETE are intended for actions that may cause side effects either on the server, or external side effects such as financial tra nsactions or transmission of email n HTTP Status code 1 1 xx Informational 2 2 xx Success 3 3 xx Redirection 4 4 xx Client Error 5 5 xx Server Error n n n

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity. n A different

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

import java. io. *; import java. util. *; import javax. servlet. http. *; public

import java. io. *; import java. util. *; import javax. servlet. http. *; public class Date. Servlet extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { // Get the Http. Session object. Http. Session hs = request. get. Session(true); // Get writer. response. set. Content. Type("text/html"); Print. Writer pw = response. get. Writer(); pw. print("<B>");

// Display date/time of last access. Date date = (Date)hs. get. Attribute("date"); if(date !=

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

URL Rewriting. n n You can append some extra data on the end of

URL Rewriting. n n 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

URLs can be rewritten or encoded to include session information. n • URL rewriting

URLs can be rewritten or encoded to include session information. n • URL rewriting usually includes a session id. n • 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=688 Advantages: – Let user remain anonymous. – They are universally supported(most styles). • Disadvantages: – Tedious to rewrite all URLs. – Only works for dynamically created documents. n

URL Rewriting

URL Rewriting

import javax. servlet. *; import javax. servlet. http. *; import java. io. *; import

import javax. servlet. *; import javax. servlet. http. *; import java. io. *; import java. util. *; public class URLRewriting. Servlet extends Http. Servlet { //Initialize global variables public void init(Servlet. Config config) throws Servlet. Exception { super. init(config); } //Process the HTTP Get request public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println("<html>"); out. println("<head><title>URL Rewriting</title></head>"); out. println("<body>");

// Encode a URL string with the session id appended to it. String url

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

Hidden Form Fields n n Hidden form fields are another way to support session

Hidden Form Fields n n 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. <FORM ACTION="/servlet/Show. Parameters" METHOD="POST">. . . <INPUT TYPE="HIDDEN" NAME="OCCUPATION“ VALUE="ENGINEER"> <INPUT TYPE="HIDDEN" NAME="SESSIONID" VALUE="194043">. . . </FORM>

Cont. . n n n n n Fields can have identification (session id) or

Cont. . n n n n n Fields can have identification (session id) or just some thing to remember (occupation). Servlet reads the fields using req. get. Parameter(). 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.