Java Reference
In-Depth Information
Using Cookies
Many websites can be customized to keep track of information about you and the fea-
tures you want the site to display. This customization is possible because of a web
browser feature called cookies , small files containing information that a website wants to
remember about a user, such as a username, the number of visits, and the like. The files
are stored on the user's computer, and a website can read only the cookies on the user's
system that the site has created.
Because of privacy considerations, most web browsers can be configured to reject all
cookies or ask permission before allowing a site to create a cookie. The default behavior
for most browsers is to accept all cookies.
With servlets, you can easily create and retrieve cookies as a user runs your application.
Cookies are supported by the Cookie class in the javax.servlet.http package.
To create a cookie, call the Cookie( String , String ) constructor. The first argument is
the name you want to give the cookie, and the second is the cookie's value.
One use for cookies is to count the number of times someone has loaded a servlet. The
following statement creates a cookie named visits and gives it the initial value of 1 :
Cookie visitCookie = new Cookie(“visits”, “1”);
When you create a cookie, you must decide how long it should remain valid on a user's
computer. Cookies can be valid for an hour, a day, a year, or any time in between. When
a cookie is no longer valid, the web browser deletes it automatically.
Call a cookie's setMaxAge( int ) method to set the amount of time the cookie remains
valid, in seconds. If you use a negative value as an argument, the cookie remains valid
only while the user's web browser is open. If you use 0 as a value, the cookie is not
stored on a user's computer.
The purpose of creating a cookie with a maximum age of 0 is to
tell the web browser to delete the cookie if it already has one.
NOTE
Cookies are sent to a user's computer along with the data displayed by the web browser.
To send a cookie, call the addCookie( Cookie ) method of an HttpServletResponse
object.
21
You can add more than one cookie to a response. When cookies are stored on a user's
computer, they're associated with the URL of the web page or program that created the
cookie. You can associate several cookies with the same URL.
Search WWH ::




Custom Search