To send cookies to the client, a servlet would create one or more
cookies with the appropriate names and values via new
Cookie(name, value) (section 2.1), set any desired
optional attributes via cookie.setXxx (section 2.2),
and add the cookies to the response headers via
response.addCookie(cookie) (section 2.3). To read
incoming cookies, call request.getCookies(), which
returns an array of Cookie objects. In most cases,
you loop down this array until you find the one whose name
(getName) matches the name you have in mind, then
call getValue on that Cookie to see the
value associated with that name. This is discussed in section
2.4.
2.1 Creating Cookies
A Cookie
is created by calling the Cookie constructor, which
takes two strings: the cookie name and the cookie value. Neither
the name nor the value should contain whitespace or any of:
[ ] ( ) = , " / ? @ : ;
2.2 Reading and Specifying Cookie Attributes
Before adding the cookie to the outgoing headers, you can look up
or set attributes of the cookie. Here's a summary:
- getComment/setComment
- Gets/sets a comment associated with this cookie.
- getDomain/setDomain
- Gets/sets the domain to which cookie applies. Normally, cookies
are returned only to the exact hostname that sent them. You can
use this method to instruct the browser to return them to other
hosts within the same domain. Note that the domain should start
with a dot (e.g. .
prenhall.com), and must contain two dots for
non-country domains like .com, .edu, and .gov, and three dots for
country domains like .co.uk and .edu.es.
- getMaxAge/setMaxAge
- Gets/sets how much time (in seconds) should elapse before the cookie expires.
If you don't set this, the cookie will last only for the current session
(i.e. until the user quits the browser), and will not be stored on disk.
See the
LongLivedCookie class below, which defines a subclass of
Cookie with a maximum age automatically set one year in the future.
- getName/setName
- Gets/sets the name of the cookie. The name and the value are the two
pieces you virtually always care about. Since the
getCookies
method of HttpServletRequest returns an array of Cookie objects,
it is common to loop down this array until you have a particular
name, then check the value with getValue. See the getCookieValue
method shown below.
- getPath/setPath
- Gets/sets the path to which this cookie applies. If you don't specify
a path, the cookie is returned for all URLs in the same directory
as the current page as well as all subdirectories. This method can
be used to specify something more general. For example,
someCookie.setPath("/") specifies that all pages on the server
should receive the cookie. Note that the path specified must include
the current directory.
- getSecure/setSecure
- Gets/sets the
boolean value indicating whether the cookie should
only be sent over encrypted (i.e. SSL) connections.
- getValue/setValue
- Gets/sets the value associated with the cookie. Again, the name and the
value are the two parts of a cookie that you almost always care about,
although in a few cases a name is used as a boolean flag, and its value
is ignored (i.e the existence of the name means true).
- getVersion/setVersion
- Gets/sets the cookie protocol version this cookie complies with.
Version 0, the default, adheres to the original Netscape specification.
Version 1, not yet widely supported, adheres to
RFC 2109.
2.3 Placing Cookies in the Response Headers
The cookie is added to the Set-Cookie response header by means of the
addCookie method of HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);
2.4 Reading Cookies from the Client
To send cookies to the client, you created a Cookie
then used addCookie to send a Set-
Cookie HTTP response header. This was discussed above in
section 2.1. To read the cookies that come back from the client,
you call getCookies on the
HttpServletRequest. This returns an array of
Cookie objects corresponding to the values that came
in on the Cookie HTTP request header. Once you have
this array, you typically loop down it, calling
getName on each Cookie until you find
one matching the name you have in mind. You then call
getValue on the matching Cookie, doing some
processing specific to the resultant value. This is such a common
process that the following section presents a simple
getCookieValue method that, given the array of
cookies, a name, and a default value, returns the value of the
cookie matching the name, or, if there is no such cookie, the
designated default value.
NEXT
This tutorial is now available as a book: Core Servlets and JavaServer Pages by Marty Hall, published by Sun Microsystems Press.
Read all about it at CoreServlets.com
Server-Side Web Applications using Java Servlets versions 2.1/2.2 and JavaServer Pages (JSP) version 1.0: A Tutorial
© 1999-2000 Marty Hall.
All source code freely available for unrestricted use.
Created for work in the Research and Technology Development Center of the Johns Hopkins University Applied Physics Lab, for courses in the Johns Hopkins Part-Time MS Program in Computer Science, and for various industry seminars and on-site Java short courses.
Please note that this is a first draft of the tutorial, so please send corrections, comments, and suggestions to me at hall@apl.jhu.edu.
Reprinted with permission from the author. Click here to visit the original version
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|