Introduction to Cookie

Introduction to Cookie


Posted in : Servlet Posted on : November 9, 2010 at 6:51 PM Comments : [ 0 ]

This section contains the Introduction to Cookie.

Introduction to Cookie

Cookies are small text files. To keep Track of all the users, Application server store it in client browser. Cookie stores value in the form of name/value pairs. For example, a Cookie can have a name "user" with the value "Ankit". They are created by the server and are sent to the client with the HTTP response headers. Cookie saves in the local hard disk of client. They sends to server along with HTTP request headers.

A Cookie can have a maximum size of 4 bytes. A web browser generally supports 20 cookies per host. Some key characteristics of the Cookie are given below :

  • Cookies can only be read by the application server that had written them in the client browser.

  • Cookies can be used by the server to find out the computer name, IP address or any other details of the client computer by retrieving the remote host address of the client where the cookies are stored.

The Servlet API provides support for cookies. The Cookie class of javax.servlet.http package represents a cookie. The Cookie class provides a constructor that accepts the name and value to create a cookie. The following code snippet shows the constructor for creating a cookie with name, name, and value,
value:

public Cookie(String name, String value);

The HttpServletResponse interface provides the addCookie() method to add a cookie to the response object, for sending it to the client. The following code snippet shows how to add a cookie:

resp.addCookie(Cookie cookie);

The HttpServletRequest class provides the getCookies() method that returns an array of cookies that the request object contains. The following code snippet shows how to retrieve cookies:

Cookie cookie[] = req.getCookies();

The Cookie class provides several methods to set and retrieve various properties of a cookie. The following table describes the various methods of the Cookie class :

  Method         Description       
public String getName() Returns the name of the cookie.
public void setMaxAge(int expiry) Sets the maximum time for which
the client browser retains the
cookie value.
public int getMaxAge() Returns the maximum age of the
cookie in seconds.
public void setValue(String value) Sets a new value to the cookie.
public String getValue() Returns the value of the cookie.
Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics