Lesson 7 | Request.Cookies |
Objective | Read user data written during a prior visit. |
ASP Request.Cookies
HTTP is known as a "stateless" protocol.
After a browser and server have completed an HTTP transaction,
no information (such as data submitted through an HTML Form) is retained. This loss of user information occurs when the user moves from page to page
in a Web site and when a user leaves one Web site for another.
Cookies were developed as a way to retain user data between Web pages or visits to a Web site. A cookie consists of one or more name-value pairs sent to a browser from a Web server. The browser stores these cookies in a text file (called cookie.txt).
Although you cannot store much information in any one cookie, they are still useful for:
- Identifying returning users: Many sites store a unique user ID in a cookie and then use the cookie value to retrieve user information from a database.
- Tracking a user's order: Many sites that maintain "shopping carts" to store a record of items to be purchased use cookies to track the cart's contents.
- ASP's Session object: The ASP Session object uses a session cookie (different from a browser cookie) to retain user information as the user goes to various parts of the Web site.
In this lesson, we explain retrieving cookie values that were set prior to our reading them. Setting initial or updated cookie values uses the ASP Response object, which will be described in an upcoming lesson.
Reading a T-shirt cookie
On our course project T-shirt store Web site, we could use a cookie to store the preferred T-shirt size for a customer to avoid requesting this same information each time the user visits the site. Once the cookie, called "ShirtSize"
, had been created, we could read the cookie's contents and write the value (for example, XL
) to the user's browser with this code segment:
<TD>Preferred size:</TD>
<TD><%= Request.Cookies("ShirtSize") %></TD>
And here is what is displayed on the user's browser:
Preferred size: XXL
Multiple-value cookies
The previous example used a single-value cookie, but you can also create nested cookies, or
keys[1].
For example, we could store all the user's T-shirt preferences in a single cookie and have keys store attributes like size, color, and crew neck vs. V-neck.
When the user returned to our Web site, we could store or display those
preferences in a table after reading them from the cookie. Because we can reference each piece of data, we could use our user's information to display only that part of our inventory that matches our user's preferences. The next lesson describes the ASP Response object.
[1]Key: A key specifies a particular element within a collection. For example a collection of first names might use a last name as a key, and Bill Smith's first name could be retrieved with: FirstNames("Smith").