Chapter 10. Reading and Setting Cookies

Introduction

In a typical visit to a web site, a user sends multiple requests for resources to a web server. If a web page contains many images (and most do!), then requesting the single web page involves one HTTP request for the HTML code and other template text (such as headlines and phrases), followed by separate requests for each image the web page contains. Future requests for the same page often return versions of these text and images that are cached on the client’s computer for the sake of efficiency, depending on whether the fetched resources permit caching. At any rate, the server views each HTTP request for these web resources as separate and discrete from the other requests. Without the use of additional protocols, the server does not have a mechanism for managing client state , such as the progress of a web user through a questionnaire or storefront. Being able to logically relate one or more web requests as a single user session is where cookies come in.

A cookie is a small piece of information on a user’s computer that a web server can use to identify that user the next time he visits the site. When a user initially visits the cookie-enabled site, the server responds with an extra response header that looks like:

Set-Cookie: mycookie=1051565332678; Domain=.myorg.com;
Expires=Tue, 29-Apr-2003 07:42:12 GMT

Consequently, when the user visits the same site, his browser sends an extra request header that contains the cookie associated ...

Get Java Servlet & JSP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.