What is Cookie ?



Cookies are a mechanism that a servlet uses to have clients hold a small amount of state-information associated with the user. Servlets can use the information in a cookie as the user enters a site (as a low-security user sign-on, for example), as the user navigates around a site (as a repository of user preferences for example), or both.

Handling All Browsers through Cookie

By default, session tracking uses cookies to associate a session identifier with a user. To also support users that access a servlet with a browser that does not support cookies, or that is set up to reject cookies, you must use URL rewriting instead.

When you use URL rewriting you call methods that, when necessary, include the session ID in a link. You must call these methods for every link in the servlet response. The method that associates a session ID with a URL is HttpServletResponse.encodeURL. If you redirect the user to another page, the method to associate the session ID with the redirected URL is called

HttpServletResponse.encodeRedirectURL.

The URL encoding and encoding redirect methods decide whether the URL needs to be rewritten, and return the URL either changed or unchanged. (The rules for URLs and redirected URLS differ, but in general if the server detects that the browser supports cookies, then the URL is not rewritten.)

The version of the Duke's Bookstore example that uses URL rewriting has the following code in
CatalogServlet:
//Print out info on each book in its own two rows
out.println(" " + ...
"
response.encodeURL("/bookstore/bookdetails?bookId=" +
bookId) +
"\"> " + books[i].getTitle() +"
" + ..."
response.encodeURL("/bookstore/catalog?Buy=" + bookId)
+ "\"> Add to Cart
" +
Notice that the CatalogServlet returns two links to the user for each book. One link offers details about the book and the other allows you to add the book to your shopping cart. Both URLs would be rewritten because, again, every link that the servlet returns to the user must be rewritten when URL rewriting is used.

If the user clicks on a link with a rewritten URL, the servlet recognizes and extracts the session ID. Then the getSession method uses the session ID to get the user's HttpSession object.

On the other hand, if the user's browser does not support cookies and the user clicks on an un-rewritten URL, the user's session is lost. The servlet contacted through that link creates a new session, but the new session does not have the data associated with the previous session. Once a servlet loses the session data, the data is lost for all servlets that share the session. You should consistently use URL rewriting if your servlet is to support clients that do not support or accept cookies.


Importance of Cookies




Cookies are a way for a server (or a servlet, as part of a server) to send some information to a client to store, and for the server to later retrieve its data from that client. Servlets send cookies to clients by adding fields to HTTP response headers. Clients automatically return cookies by adding fields to HTTP request headers.

Each HTTP request and response header is named and has a single value. For example, a cookie could be a header named BookToBuy with a value 304qty1, indicating to the calling application that the user wants to buy one copy of the book with stock number 304. (Cookies and their values are application-specific.) Multiple cookies can have the same name. For example, a servlet could send two cookies with headers named BookToBuy; one could have the value shown previously, 304qty1, while the other could have a value 301qty3.


These cookies would indicate that the user wants to buy one copy of the book with stock number 304, and three copies of the book with stock number 301.

In addition to a name and a value, you can also provide optional attributes such as comments. Current web browsers do not always treat the optional attributes correctly, so you should not rely on them.
A server can provide one or more cookies to a client. Client software, such as a web browser, is expected to support twenty cookies per host, of at least four kilobytes each.


When you send a cookie to a client, standard HTTP/1.0 caches will not cache the page. Currently, the
javax.servlet.http.Cookie does not support HTTP/1.1 cache control models.

Cookies that a client stores for a server are returned by the client to that server and only that server. A server can contain multiple servlets; the Duke's Bookstore example is made up of multiple servlets running within a single server. Because cookies are returned to a server, servlets running within a server share cookies.

The examples in this section illustrate this by showing the CatalogServlet and ShowCart servlet working with the same cookies.

Creating a Cookie

The constructor for thejavax.servlet.http.Cookie class creates a cookie with an initial name and value.
You can change the value of the cookie later with its setValue method.

The value of the cookie can be any string, though null values are not guaranteed to work the same way on all browsers. In addition, if you are sending a cookie that complies with Netscape's original cookie specification, do not use whitespace or any of these characters:

[ ] ( ) = , " / ? @ : ;

If your servlet returns a response to the user with a Writer, create the cookie before accessing the Writer.(Because cookies are sent to the client as a header, and headers must be written before accessing the Writer.)

If the CatalogServlet used cookies to keep track of a client's book order, the servlet could create cookies likethis:

//If the user wants to add a book, remember it by adding a cookie
if (bookId != null) {
Cookie getBook = new Cookie("Buy", bookId);
...
}




Setting Cookie Attributes

The Cookie class provides a number of methods for setting a cookie's values and attributes. Using these methods is straightforward; they are explained in the javadoc for Cookie class.

The following example sets the comment field of the CatalogServlet's cookie. The comment field describes the purpose of the cookie.

getBook.setComment("User wants to buy this book " + "from the bookstore.");

You can also set the maximum age of the cookie. This attribute is useful, for example, for deleting a cookie. Once again, if Duke's Bookstore kept track of a user's order with cookies, the example would use this attribute to delete a book from the user's order. The user removes a book from the shopping cart in the ShowCartServlet; its code would look something like this:

thisCookie.setMaxAge(0);

Sending the Cookie

Cookies are sent as headers of the response to the client; they are added with the addCookie method of the HttpServletResponse class. If you are using a Writer to return text data to the client, you must call the
addCookie method before calling the HttpServletResponse's getWriter method.
Continuing the example of the CatalogServlet, the following is code for sending the cookie:
response.addCookie(getBook);

Retrieving Cookies
Clients return cookies as fields added to HTTP request headers. To retrieve any cookie, you must retrieve all the cookies using the getCookies method of the HttpServletRequest class.

// Find the cookie that pertains to the book to remove
Cookie[] cookies = request.getCookies();
...

// Delete the book's cookie by setting its maximum age to zero
thisCookie.setMaxAge(0);
}

Getting the Value of a Cookie

To find the value of a cookie, use its getValue method. To continue the ShowCartServlet example:

Cookie[] cookies = request.getCookies();

for(i=0; i < cookies.length; i++) {
Cookie thisCookie = cookie[i];
if (thisCookie.getName().equals("Buy") &&
thisCookie.getValue().equals(bookId)) {

// Delete the cookie by setting its maximum age to zero

thisCookie.setMaxAge(0); } }

Keywords: Cookie, Getting the cookie value, cookie attributes, how to create a cookie, definition of cookie, why use cookie,cookie value