Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
186
Chapter 8 Handling Cookies
Placing Cookies in the Response Headers
The cookie is inserted into a
Set Cookie
HTTP response header by means
of the
addCookie
method of
HttpServletResponse
. The method is called
addCookie
, not
setCookie
, because any previously specified
Set Cookie
headers are left alone and a new header is set. Here s an example:
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // 1 year
response.addCookie(userCookie);
Reading Cookies from the Client
To send cookies to the client, you create a
Cookie
, then use
addCookie
to
send a
Set Cookie
HTTP response header. To read the cookies that come
back from the client, you call
getCookies
on the
HttpServletRequest
. This
call returns an array of
Cookie
objects corresponding to the values that came in
on the
Cookie
HTTP request header. If there are no cookies in the request,
getCookies
returns
null
. 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
and finish with
some processing specific to the resultant value. This is such a common process
that Section 8.5 presents two utilities that simplify retrieving a cookie or cookie
value that matches a designated cookie name.
8.4 Examples of Setting and
Reading Cookies
Listing 8.1 and Figure 8 1 show the
SetCookies
servlet, a servlet that sets
six cookies. Three have the default expiration date, meaning that they should
apply only until the user next restarts the browser. The other three use
set
MaxAge
to stipulate that they should apply for the next hour, regardless of
whether the user restarts the browser or reboots the computer to initiate a
new browsing session.
Listing 8.2 shows a servlet that creates a table of all the cookies sent to
it in the request. Figure 8 2 shows this servlet immediately after the
SetCookies
servlet is visited. Figure 8 3 shows it after
SetCookies
is vis
ited then the browser is closed and restarted.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved