Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site or domain later. By having the server read information it sent the client previously, the site can provide visitors with a number of conveniences:
- Identifying a user during an e-commerce session. Many on-line stores use a “shopping cart” metaphor in which the user selects an item, adds it to his shopping cart, then continues shopping. Since the HTTP connection is closed after each page is sent, when the user selects a new item for his cart, how does the store know that he is the same user that put the previous item in his cart? Cookies are a good way of accomplishing this. In fact, this is so useful that servlets have an API specifically for this, and servlet authors don’t need to manipulate cookies directly to make use of it. This is discussed in the tutorial section on Session Tracking.
- Avoiding username and password. Many large sites require you to register in order to use their services, but it is inconvenient to remember the username and password. Cookies are a good alternative for low-security sites. When a user registers, a cookie is sent with a unique user ID. When the client reconnects at a later date, the user ID is returned, the server looks it up, determines it belongs to a registered user, and doesn’t require an explicit username and password.
- Focusing advertising. The search engines charge their customers much more for displaying “directed” ads than “random” ads. That is, if you do a search on “Java Servlets”, a search site can charge much more for an ad for a servlet development environment than an ad for an on-line travel agent. On the other hand, if the search had been “Bali Hotels”, the situation would be reversed. The problem is that they 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. Cookies let them remember “Oh, that’s the person who was searching for such and such previously” and display an appropriate (read “high priced”) ad instead of a random (read “cheap”) one.