Cookie Class |
public class Cookie extends Object implements Cloneable |
    Object
        Cookie
Interfaces Cloneable A Cookie is an object that resides on a client machine and contains state information. A Cookie has a name, a single value and some other optional information. Cookies can be used to identify a particular user and provide information such as name, address, account number, etc. A cookie is sent by a server to a Web browser, saved on the client machine, and can later be sent back to the server. The optional information that can be attached to a Cookie includes an expiration date, path and domain qualifiers, a version number, and a comment. The expiration date specifies when the Cookie will be deleted from the client machine. If no date is given, the Cookie is deleted when the session ends. A servlet sends cookies to a browser using the addCookie() method defined in the HttpServletResponse interface. This method adds fields to the HTTP response header. The browser returns cookies to the servlet by adding fields to the HTTP request header. Cookies can be retrieved from a request by invoking the getCookies() method defined in the HttpServletRequest interface. Example: Using Cookies In this example a Cookie is used to store some user data. When the servlet is invoked, the doGet() method returns an HTML file containing textfield and a Submit button to the browser. The method first determines if a Cookie was attached to the request. If it was, the textfield is initialized with the value of the Cookie. If there was no Cookie, the textfield is initially blank. The user can change the contents of the textfield or leave it the way it is. When the Submit button is pressed, the doPost() method of the servlet is called. This method extracts the contents of the textfield and adds a Cookie containing the textfield contents as its value to the response. The response consists of a confirmation of the textfield contents. The Cookie is set to live on the client machine for five minutes.
       import javax.servlet.*;
       import javax.servlet.http.*;
       import java.io.*;
       public class CookieServlet extends HttpServlet {
         String companyName;
         String value = "";
         // The doGet() method is called when the servlet is invoked.
         // It sends a simple form back to the client.
         public void doGet(HttpServletRequest request,
             HttpServletResponse response) throws ServletException,
         IOException {
         // see if a cookie exists and if it does extract its value.
         Cookie[] cookies = request.getCookies();
         for (int i = 0; i < cookies.length; ++i) {
          String name = cookies[i].getName();
         if (name != null && name.equals("companyName")) {
         value = cookies[i].getValue();
         }
         }
         // Set the response type to html

    response.setContentType("text/html");
         // Open a character output stream to the client machine and write
         // the response.  If a cookie existed, the textfield will be
         // intialized with its value.  Otherwise, the textfield will be blank.
         // Note that the value passed to the textfield is surrounded by
         // double-quotes to allow for multi-word strings.
         char dq = '\"';
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE> Cookie Example </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("<FORM METHOD=POST>");
         pw.println("Company Name <INPUT TYPE=TEXT NAME=name VALUE=" + dq
         + value + dq + "><BR>");
         pw.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

    pw.println("</FORM></BODY></HTML>");
         pw.close();
         }

         // The doPost() method receives the form from the client and sends
         // back a confirmation.  It also writes a cookie containing the
         // String that was written into the textfield.
         public void doPost(HttpServletRequest request,
         HttpServletResponse response) throws ServletException,
         IOException {
         // Get the contents of the textfield.
         companyName = request.getParameter("name");
         // Create a cookie that contains the contents of the textfield.
         // The cookie is set to live for 5 minutes and is added to the
         // response.
         Cookie nameCookie = new Cookie("companyName", companyName);
         nameCookie.setMaxAge(300);
         response.addCookie(nameCookie);

    response.setContentType("text/html");
         // Open a character output stream to the client machine and write
         // the response
         PrintWriter pw = response.getWriter();
         pw.println("<HTML> <HEAD> <TITLE>" + companyName
         + " information </TITLE>");

    pw.println("</HEAD><BODY>");
         pw.println("Company: " + companyName + "<BR>");

    pw.println("</BODY></HTML>");
         pw.close();
         }
       }
The first time the servlet is invoked, no cookie exists and the textfield is empty. Type something in and press the Submit button. Now, exit the Web browser and shut down the server. Restart the server and reload the servlet into the Web browser. A cookie now exists and the text field will be initialized with whatever was previously typed in to the textfield.

Cookie() |
public Cookie(String name, String value) | Constructor
Creates a Cookie object with a specified name and value. The name must consist only of alphanumeric characters. Once the name is set by the constructor, it cannot be changed.

clone() |
public Object clone() | Method
clone() overrides the clone() method from the Object class to return a copy of the invoking Cookie object.

getComment() |
public String getComment() | Method
A Cookie can contain a comment that is usually used to describe the purpose of the Cookie. getComment() returns the comment associated with the invoking Cookie object, or null if there is no comment.

setComment() |
public void setComment(String comment) | Method
A Cookie can contain a comment that is usually used to describe the purpose of the Cookie. setComment() changes or sets the comment associated with the invoking Cookie object.

getMaxAge() |
public int getMaxAge() | Method
getMaxAge() returns the length of time in seconds that the Cookie will persist on the user's machine. A return value of –1 indicates that the cookie will persist until the browser shuts down.

setMaxAge() |
public void setMaxAge(int duration) | Method
setMaxAge()sets the length of time in seconds that the Cookie will persist on the user's machine. A negative value means the Cookie will not be stored on the user's machine and will be deleted when the browser terminates. A value of zero means the Cookie will be deleted immediately.

getName() |
public String getName() | Method
getName() returns the name of the invoking Cookie object.

getDomain() |
public String getDomain() | Method
getDomain() returns the domain name set for the invoking Cookie object.

getPath() |
public String getPath() | Method
getPath() returns the path on the server where the browser will return the invoking Cookie object.

setDomain() |
public void setDomain(String domain) | Method
setDomain() sets the domain name within which the Cookie will be visible.

setPath() |
public void setPath(String path) | Method
setPath() specifies the path on the server where the browser will return the invoking Cookie object. The Cookie will also be visible to all sub-directories of the specified path.

getSecure() |
public boolean getSecure() | Method
getSecure() returns true if the browser will send the invoking Cookie object using a secure protocol.

setSecure() |
public void setSecure(String value) | Method
setSecure() specifies whether the browser should send the invoking Cookie object using a secure protocol. The default is false, meaning the Cookie will be sent using any protocol.

getValue() |
public String getValue() | Method
getValue() returns a String containing the value of the invoking Cookie object.

setValue() |
public void setValue(String value) | Method
setValue()changes the value of the invoking Cookie object.

getVersion() |
public int getVersion() | Method
One optional piece of information a Cookie can contain is the version number of the protocol with which the Cookie complies. getVersion() returns 0 if the invoking Cookie object complies with the original Netscape specification, or 1 if it complies with RFC 2109.

setVersion() |
public void setVersion(int version) | Method
One optional piece of information a Cookie can contain is the version number of the protocol with which the Cookie complies. setVersion() sets the version number of the protocol with which the Cookie complies.