Java Reference
In-Depth Information
L ISTING 5.2
Continued
//Get Servlet information
public String getServletInfo() {
return “CookieServlet Information”;
}
}
Every time the CookieServlet services a request, it checks for cookies in the
HttpServletRequest . It does this by calling the HttpServletRequest.getCookies() method.
If the request does contain cookies, the servlet will iterate over the list of cookies looking for a
cookie with the name session_id .
If the request contains no cookies or the list of cookies does not contain a cookie named
session_id , you create one and add it to the response. The code snippet that does this is listed
as follows:
response.addCookie(new Cookie(“session_id”, “564XX892”));
N OTE
Cookies are stored in the response as HTTP headers. Therefore, you must add cookies
to the response before adding any other content.
The best way to test this functionality is to open your browser to the CookieServlet . The first
time it runs, you should get a response that says “Welcome to our site, we have created a ses-
sion for you.” After you get this message, click the Refresh button. You should see a new
response that says “Hello : Bob.” The servlet can now identify the user “Bob” by the session
ID stored as a cookie.
N OTE
If you have trouble running this example, make sure the use of cookies is enabled in
your browser.
5
 
Search WWH ::




Custom Search