Java Reference
In-Depth Information
Session variables allow much more interesting and dynamic Web sites to be
created. However, they do not allow a user's personal details/preferences to be
maintained between visits to the same site. The next section will show how this
may be done.
8.9
Cookies
Cookies provide another means of storing a user's data for use whilst he/she is navi-
gating a Web site. Whereas sessions provide data only for the duration of one visit
to the site, though, cookies store information that may be retrieved on subsequent
visits to the site. (In actual fact,
Session
objects make use of
Cookie
objects.) They
can be used to personalise pages for the user and/or select his/her preferences.
Cookies have been used by CGI programmers for years and the developers of Java's
servlet API incorporated this de facto standard into the servlet specifi cation. What
is
a cookie, though?
A cookie is an associated name-value pair in which both name and value are
strings. (E.g., “username” and “Bill Johnson”.) It is
possible
to maintain a cookie
simply for the duration of a browsing session, but it is usually stored
on the client
computer
for future use. Each cookie is held in a small fi le sent by the server to the
client machine and retrieved by the server on subsequent visits by the user to the
site. The constructor for a Java
Cookie
object
must
have this signature:
Cookie(String <name>, String <name>)
(Note that there is no default constructor.)
Once a cookie has been created, it must be added to the
HttpServletResponse
object via the following
HttpServletResponse
method :
void addCookie(Cookie <name>)
For example:
response.addCookie(myCookie);
Cookies are retrieved via the following method of class
HttpServletRequest
:
Cookie[] getCookies()
For example:
Cookie[] cookie = request.getCookies();
The lifetime of cookie is determined by method
setMaxAge
, which specifi es the
number of seconds for which the cookie will remain in existence (usually a rather
large number!). If any negative value is specifi ed, then the cookie goes out of exis-
tence when the client browser leaves the site. A value of zero causes the cookie's
immediate destruction. Other useful methods of the
Cookie
class (with pretty obvi-
ous purposes) are shown below.
Search WWH ::
Custom Search