Cookies

67 pages
5 views

Please download to get full document.

View again

of 67
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Share
Description
1. HANDLING COOKIES Topics in This Chapter ã Understanding the benefits and drawbacks of cookies ã Sending outgoing cookies ã Receiving incoming cookies ã…
Transcript
  • 1. HANDLING COOKIES Topics in This Chapter • 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 Training courses from the book’s author: http://courses.coreservlets.com/ • Personally developed and taught by Marty Hall • Available onsite at your organization (any country) • Topics and pace can be customized for your developers • Also available periodically at public venues • Topics include Java programming, beginning/intermediate servlets and JSP, advanced servlets and JSP, Struts, JSF/MyFaces, Ajax, GWT, Ruby/Rails and more. Ask for custom courses! © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 2. 8 Training courses from the book’s author: http://courses.coreservlets.com/ • Personally developed and taught by Marty Hall • Available onsite at your organization (any country) • Topics and pace can be customized for your developers • Also available periodically at public venues • Topics include Java programming, beginning/intermediate servlets and JSP, advanced servlets and JSP, Struts, JSF/MyFaces, Ajax, GWT, Ruby/Rails and more. Ask for custom courses! Cookies are small bits of textual information that a Web server sends to a browser and that the browser later returns unchanged when visiting the same Web site or domain. By letting the server read information it sent the client previously, the site can provide visitors with a number of conveniences such as presenting the site the way the visitor previously customized it or letting identifiable visitors in without their having to reenter a password. This chapter discusses how to explicitly set and read cookies from within servlets, and the next chapter shows how to use the servlet session tracking API (which can use cookies behind the scenes) to keep track of users as they move around to differ- ent pages within your site. 8.1 Benefits of Cookies There are four typical ways in which cookies can add value to your site. We summa- rize these benefits below, then give details in the rest of the section. • Identifying a user during an e-commerce session. This type of short-term tracking is so important that another API is layered on top of cookies for this purpose. See the next chapter for details. © Prentice Hall and Sun Microsystems Press. Personal use only. 229
  • 3. J2EE training from the author: http://courses.coreservlets.com/ 230 Chapter 8 ■ Handling Cookies • Remembering usernames and passwords. Cookies let a user log in to a site automatically, providing a significant convenience for users of unshared computers. • Customizing sites. Sites can use cookies to remember user preferences. • Focusing advertising. Cookies let the site remember which topics interest certain users and show advertisements relevant to those interests. Identifying a User During an E-commerce Session Many online stores use a “shopping cart” metaphor in which users select items, add them to their shopping carts, then continue shopping. Since the HTTP connection is usually closed after each page is sent, when a user selects a new item to add to the cart, how does the store know that it is the same user who put the previous item in the cart? Persistent (keep-alive) HTTP connections do not solve this problem, since persistent connections generally apply only to requests made very close together in time, as when a browser asks for the images associated with a Web page. Besides, many older servers and browsers lack support for persistent connections. Cookies, however, can solve this problem. In fact, this capability is so useful that servlets have an API specifically for session tracking, and servlet and JSP authors don’t need to manipulate cookies directly to take advantage of it. Session tracking is discussed in Chapter 9. Remembering Usernames and Passwords Many large sites require you to register to use their services, but it is inconvenient to remember and enter the username and password each time you visit. Cookies are a good alternative for low-security sites. When a user registers, a cookie containing a unique user ID is sent to him. When the client reconnects at a later date, the user ID is returned automatically, the server looks it up, determines it belongs to a registered user that chose autologin, and permits access without an explicit username and pass- word. The site might also store the user’s address, credit card number, and so forth in a database and use the user ID from the cookie as the key to retrieve the data. This approach prevents the user from having to reenter the data each time. For example, when Marty travels to companies to give onsite JSP and servlet training courses, he typically checks both travelocity.com and expedia.com for flight information. These both require usernames and passwords to search flight schedules, but have different rules about which characters are legal in usernames and how many characters are required for passwords. So, Marty has a difficult time remembering © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 4. J2EE training from the author: http://courses.coreservlets.com/ 8.2 Some Problems with Cookies 231 how to log in. Fortunately, both sites use the cookie scheme described in the preced- ing paragraph, simplifying Marty’s access from his personal desktop or laptop machine. Customizing Sites Many “portal” sites let you customize the look of the main page. They might let you pick which weather report you want to see (yes, it is still raining in Seattle), what stock symbols should be displayed (yes, your stock is still way down), what sports results you care about (yes, the Orioles are still losing), how search results should be displayed (yes, you want to see more than one result per page), and so forth. Since it would be inconvenient for you to have to set up your page each time you visit their site, they use cookies to remember what you wanted. For simple settings, the site could accomplish this customization by storing the page settings directly in the cookies. For more com- plex customization, however, the site just sends the client a unique identifier and keeps a server-side database that associates identifiers with page settings. Focusing Advertising Most advertiser-funded Web sites charge their advertisers much more for displaying “directed” (or “focused”) ads than for displaying “random” ads. Advertisers are gener- ally willing to pay much more to have their ads shown to people that are known to have some interest in the general product category. Sites reportedly charge advertisers as much as 30 times more for directed ads than for random ads. For example, if you go to a search engine and do a search on “Java Servlets,” the search site can charge an advertiser much more for showing you an ad for a servlet development environment than for an ad for an online travel agent specializing in Indonesia. On the other hand, if the search had been for “Java Hotels,” the situation would be reversed. Without cookies, sites have to show a random ad when you first arrive and haven’t yet performed a search, as well as when you search on something that doesn’t match any ad categories. With cookies, they can identify your interests by remembering your previous searches. Since this approach enables them to show directed ads on visits to their home page as well as for their results page, it nearly doubles their advertising revenue. 8.2 Some Problems with Cookies Providing convenience to the user and added value to the site owner is the purpose behind cookies. And despite much misinformation, cookies are not a serious security threat. Cookies are never interpreted or executed in any way and thus cannot be used © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 5. J2EE training from the author: http://courses.coreservlets.com/ 232 Chapter 8 ■ Handling Cookies to insert viruses or attack your system. Furthermore, since browsers generally only accept 20 cookies per site and 300 cookies total, and since browsers can limit each cookie to 4 kilobytes, cookies cannot be used to fill up someone’s disk or launch other denial-of-service attacks. However, even though cookies don’t present a serious security threat, they can present a significant threat to privacy. FOXTROT © 1998 Bill Amend. Reprinted with permission of UNIVERSAL PRESS SYNDICATE. All rights reserved. First, some people don’t like the fact that search engines can remember what they previously searched for. For example, they might search for job openings or sensitive health data and don’t want some banner ad tipping off their coworkers or boss next time they do a search. Besides, a search engine need not use a banner ad: a poorly designed one could display a textarea listing your most recent queries (“Jobs any- where except at this stupid company!”; “Will my SARS infection kill my coworkers?”; etc.). A coworker could see this information if they visited the search engine for your computer or if they looked over your shoulder when you visited it. Even worse, two sites can share data on a user by each loading small images off the same third-party site, where that third party uses cookies and shares the data with both original sites. For example, suppose that both some-search-site.com and some-random-site.com wanted to display directed ads from some-ad-site.com based on what the user searched for at some-search-site.com. If the user searched for “Java Servlets,” the search engine at some-search-site.com could return a page with the following image link: <IMG SRC="http://some-ad-site.com/banner?data=Java+Servlets" ...> Since the browser will make an HTTP connection to s ome- ad-s ite.com , some-ad-site.com can return a persistent cookie to the browser. Next, some-ran- dom-site.com could return an image link like this: <IMG SRC="http://some-ad-site.com/banner" ...> © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 6. J2EE training from the author: http://courses.coreservlets.com/ 8.2 Some Problems with Cookies 233 Since the browser will reconnect to some-ad-site.com—a site from which it got cookies earlier—it will return the cookie it previously received. Assuming that some-ad-site.com sent a unique cookie value and, in its database, associated that cookie value with the “Java Servlets” search, some-ad-site can return a directed ban- ner ad even though it is the user’s first visit to some-random-site. The doubleclick.net service was the most famous early example of this technique. (Recent versions of Netscape and Internet Explorer, however, have a nice feature that lets you refuse cookies from sites other than that to which you connected, but without disabling cookies altogether. See Figure 8–1.) Figure 8–1 Cookie customization settings for Netscape (top) and Internet Explorer (bottom). © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 7. J2EE training from the author: http://courses.coreservlets.com/ 234 Chapter 8 ■ Handling Cookies This trick of associating cookies with images can even be exploited through email if you use an HTML-enabled email reader that “supports” cookies and is associated with a browser. Thus, people could send you email that loads images, attach cookies to those images, and then identify you (email address and all) if you subsequently visit their Web site. Boo. A second privacy problem occurs when sites rely on cookies for overly sensitive data. For example, some of the big online bookstores use cookies to remember your registration information and let you order without reentering much of your personal information. This is not a particular problem since they don’t actually display your complete credit card number and only let you send books to an address that was specified when you did enter the credit card in full or use the username and pass- word. As a result, someone using your computer (or stealing your cookie file) could do no more harm than sending a big book order to your address, where the order could be refused. However, other companies might not be so careful, and an attacker who gained access to someone’s computer or cookie file could get online access to valuable personal information. Even worse, incompetent sites might embed credit card or other sensitive information directly in the cookies themselves, rather than using innocuous identifiers that are linked to real users only on the server. This embedding is dangerous, since most users don’t view leaving their computer unat- tended in their office as being tantamount to leaving their credit card sitting on their desk. The point of this discussion is twofold: 1. Due to real and perceived privacy problems, some users turn off cook- ies. So, even when you use cookies to give added value to a site, when- ever possible your site shouldn’t depend on them. Dependence on cookies is difficult to avoid in some situations, but if you can provide reasonable functionality for users without cookies enabled, so much the better. 2. As the author of servlets or JSP pages that use cookies, you should be careful not to use cookies for particularly sensitive information, since this would open users up to risks if somebody accessed the user’s com- puter or cookie files. 8.3 Deleting Cookies You will probably find it easier to experiment with the examples in this chapter if you periodically delete your cookies (or at least the cookies that are associated with local- host or whatever host your server is running on). © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 8. J2EE training from the author: http://courses.coreservlets.com/ 8.3 Deleting Cookies 235 To delete your cookies in Internet Explorer, start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies. To selectively delete cookies, press Settings, then View Files (cookie files have names that begin with Cookie:, but it is easier to find them if you choose Delete Files before View Files). See Figure 8–2. To delete your cookies in Netscape, start at the Edit menu, then choose Prefer- ences, Privacy and Security, and Cookies. Press the Manage Stored Cookies button to view or delete any or all of your cookies. Again, see Figure 8–2. Figure 8–2 Deleting cookies in Internet Explorer and Netscape. © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 9. J2EE training from the author: http://courses.coreservlets.com/ 236 Chapter 8 ■ Handling Cookies 8.4 Sending and Receiving Cookies To send cookies to the client, a servlet should use the Cookie constructor to create one or more cookies with designated names and values, set any optional attributes with cookie.setXxx (readable later by cookie.getXxx), and insert the cookies into the HTTP response headers with response.addCookie. To read incoming cookies, a servlet should call request.getCookies, which returns an array of Cookie objects corresponding to the cookies the browser has associated with your site (null if there are no cookies in the request). In most cases, the servlet should then loop down this array calling getName on each cookie until it finds the one whose name matches the name it was searching for, then call getValue on that Cookie to see the value associated with the name. Each of these topics is discussed in more detail in the following subsections. Sending Cookies to the Client Sending cookies to the client involves three steps (summarized below with details in the following subsections). 1. Creating a Cookie object. You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. 2. Setting the maximum age. If you want the browser to store the cookie on disk instead of just keeping it in memory, you use setMaxAge to specify how long (in seconds) the cookie should be valid. 3. Placing the Cookie into the HTTP response headers. You use response.addCookie to accomplish this. If you forget this step, no cookie is sent to the browser! Creating a Cookie Object You create a cookie by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain white space or any of the following characters: [ ] ( ) = , " / ? @ : ; For example, to create a cookie named userID with a value a1234, you would use the following. Cookie c = new Cookie("userID", "a1234"); © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 10. J2EE training from the author: http://courses.coreservlets.com/ 8.4 Sending and Receiving Cookies 237 Setting the Maximum Age If you create a cookie and send it to the browser, by default it is a session-level cookie: a cookie that is stored in the browser’s memory and deleted when the user quits the browser. If you want the browser to store the cookie on disk, use setMax- Age with a time in seconds, as below. c.setMaxAge(60*60*24*7); // One week Since you could use the session-tracking API (Chapter 9) to simplify most tasks for which you use session-level cookies, you almost always use the setMaxAge method when using the Cookie API. Setting the maximum age to 0 instructs the browser to delete the cookie. Core Approach When you create a Cookie object, you should normally call setMaxAge before sending the cookie to the client. Note that setMaxAge is not the only Cookie characteristic that you can modify. The other, less frequently used characteristics are discussed in Section 8.6 (Using Cookie Attributes). Placing the Cookie in the Response Headers By creating a Cookie object and calling setMaxAge, all you have done is manipu- late a data structure in the server’s memory. You haven’t actually sent anything to the browser. If you don’t send the cookie to the client, it has no effect. This may seem obvious, but a common mistake by beginning developers is to create and manipulate Cookie objects but fail to send them to the client. Core Warning Creating and manipulating a Cookie object has no effect on the client. You must explicitly send the cookie to the client with response.addCookie. To send the cookie, insert it into a Set-Cookie HTTP response header by means of the addCookie method of HttpServletResponse . The method is called addCookie, not setCookie, because any previously specified Set-Cookie headers © Prentice Hall and Sun Microsystems Press. Personal use only.
  • 11. J2EE training from the author: http://courses.coreservlets.com/ 238 Chapter 8 ■ Handling Cookies are left alone and a new header is set. Also, remember that the response headers must be set before any document content is sent to the client. Here is an example: Cookie userCookie = new Cookie("user", "uid1234"); userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year response.addCookie(userCookie); Reading Cookies from the Client To send a cookie to the client, you create a Cookie, set its maximum age (usually), then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, you should perform the following two tasks, which are summarized below and then described in more detail in the following sub- sections. 1. Call request.getCookies. This yields an array of Cookie objects. 2. Loop down the array, calling getName on each one until you find the cookie of interest. You then typically call getValue and use the value in some application-specific way. Call request.getCookies To obtain the cookies that were sent by the browser, you call getCookies on the HttpServletRequest. This call returns an array of Cookie objects correspond- ing to the values that came in on the Cookie HTTP request headers. If the request co
  • We Need Your Support
    Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

    Thanks to everyone for your continued support.

    No, Thanks