Many websites can be customized to keep track of information about you and the features 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.
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. 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.
When a web browser requests a URL, the browser checks to see whether any cookies are associated with that URL. If there are, the cookies are sent along with the request. In a servlet, call the getCookies() method of an HttpServletRequest object to receive an array of Cookie objects. You can call each cookie’s getName() and getValue() methods to find out about that cookie and do something with the data. Listing 21.2 contains ColorServlet, an extended version of the ROT-13 servlet that enables a user to select the background color of the page. The color is stored as a cookie called color, and the servlet requests the cookie from a web browser every time the servlet is loaded.