Java Servlet Cookie API Methods

Servlet Cookie: Before going into the API, first let us know what for Servlet Cookie is? For better understanding the subject is discussed in Question/Answer format.

1. What is Cookie?

For us, Cookie is a class from javax.servlet.http package. But in the open world, a Cookie represents a sweet Biscuit or Chocolate.

2. What a Servlet Cookie can store?

Servlet Cookie stores small strings of data. Cookies stay all through the session. Programmer can store the session data with Cookie object. It is another style of tracking session data (the first way is using HttpSession interface).

3. Who creates Servlet Cookie and where is stored?

Servlet Cookies are created on the server (by Servlet container) and sent to the client’s browser for temporary storage. The cookies can be sent to and fro between client and server in their conversation. Client is not aware of the entire process of Cookie management as everything is done by the server and client is kept completely transparent.

4. What Cookie can do in Servlets?

Cookies are used mainly for tracking different types of client’s information. That is, the Web server can store data on the client browser in the form of Cookie objects.

Typical uses of a Servlet Cookie are

  1. To store User name and Password
  2. To write Shopping cart in e-Commerce application
  3. Advertisement on client browser
  4. Customization of Web sites etc.

5. How Servlet Cookie stored on the client are recognized by the server later?

The Cookie object created on the server is attached to response object and sent to client. The Cookie carries implicitly (like a request header carries) the client information like name, path, host and connection type etc. and the combination of this information is used by server to know cookie is coming from which client.

6. All Servlet Cookie are same or any types exist?

Yes, there are two types of cookies and they are differentiated on their life span.

  1. Session Cookies: Session cookies get expired and deleted from browser when the browser closes, thereby, they do not carry any expiration time constraint parameter. They are stored temporarily (just for the usage of session) in the RAM memory.
  2. Persistent Cookies: As the name indicates, they persist long time on the client browser. The time of expiration can be set programmatically for each Cookie. These Cookies are stored on hard disk. The Cookie gets deleted automatically when the time or age expires.

After knowing what Servlet Cookie is, let us know constructor and methods available in the Cookie class.

Following is the Cookie class signature as defined in javax.servlet.http package.

public class Cookie extends java.lang.Object implements java.lang.Cloneable

Following is the only constructor available in Cookie class.

  • public Cookie(String str1, String str2): Constructs a cookie object with the specified name str1 and value str2. Cookie constructor takes two string parameters.

Following are the important methods as defined in Servlet Cookie class.

  1. void setComment(String whatFor): Describes the comment stating what for the cookie is. This comment can be displayed to the user when cookie is displayed. For example, I shop in an online shopping center and I clicked for some biscuits. By the time I go from office, the goods are delivered and being used by my family members. Now for whom the biscuits are? Actually the biscuits are meant for my dog. This is where I can tell to inmates of my house? I can set a message in the bill itself as comment.
  2. String getComment(): Returns the comment set earlier with setComment(String) method. I can display the comment in the bill using this method.
  3. void setDomain(String domainName): The domainName indicates the domains (servers) in which the cookie should be made available. For example, the parameter (".lorvent.com") is visible to server www.lorvent.com but not to tirumala.lorvent.com.
  4. String getDomain(): Programmer can know to what domain the cookie is set earlier with setDomain(String).
  5. void setMaxAge(int expirationTime): Gives to what extent the cookie can live on the client’s browser. The expirationTime is passed as seconds. Other way to say, this method sets the age for a cookie.
  6. int getMaxAge(): Returns the maximum age of the cookie, specified in seconds earlier with setMaxAge(int). -1 indicates the cookie will persist until browser shutdown.
  7. void setPath(String uri): Specifies a path for the cookie to which the client should return the cookie. General practice is, the cookie is returned to the same server which sent them.

    The cookie is visible to all subpaths or subdirectories on the server. For example, the path "/finance" makes cookie visible to finance directory and also all its subdirectories.

  8. getPath(): Returns the path on the server to which the browser returns the cookie. For example, /finance.
  9. void setSecure(boolean flag): Dictates how the browser should return the cookie to server. If true, it must be secure protocol like HTTPS (HyperText Transfer Protocol Secured) or SSL (Secured Socket Layer). If this is not set, the default is false indicating general protocol like HHTP.
  10. boolean getSecure(): Returns a boolean value of true if the browser is using a secure protocol to return the cookie to the server and false indicates browser is using any protocol like HTTP.
  11. String getName(): Every cookie is given a name and value, both passed to Cookie constructor. This method returns the name of the Cookie. Once name is assigned, it cannot be changed. For example,

    Cookie c1 = new Cookie("LUX", 5);

    Here the name is LUX. c1.getName() returns LUX.

  12. String getValue(): Returns the value of the cookie. In the previous statement, it is 5.
  13. void setValue(String newValue): In the previous Cookie c1, the value set is 5. If the user would like to change to 10 soaps, this method is useful.
  14. int getVersion(): Returns the version of the protocol this cookie is set to work. Returns 1 if RFC 2109 version is set or 0 when uses Netscape specifications.
  15. void setVersion(int v): Sets the version of the cookie protocol. Set with 1 if RFC 2109 is used and 0 when Netscape cookie specification is used.
  16. Object clone(): Returns a clone copy of the Cookie when the original clone() method of Object class is overridden.

Following program illustrate how to use the above methods. The methods, getName(), getValue() and Cookie constructor are illustated in Cookies Simple Shopping Cart Example. Let us write one more program.

Servlet Cookie: Client HTML Program: CookieMethods.html

  

Using Cookie Methods

web.xml entry for Servlet CookieMethods.java


  snrao1
  CookieMethods



  snrao1
  /CM

Servlet Cookie: Servlet Program: CookieMethods.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CookieMethods extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {				// default content type text/html
    PrintWriter out = res.getWriter();

				// create a Cookie object with name LUX and value 5
    Cookie c1 = new Cookie("LUX", "5");

   			        // all set methods
    c1.setComment("These biscuits are meant for Dog");
    c1.setPath("/india");
    c1.setDomain("localhost");

				// all get methods
    out.println("Cookie name: " + c1.getName()); 	
 
    out.println("

Origianl Cookie value (before reset): " + c1.getValue()); c1.setValue("10"); out.println("
Cookie value after reset: " + c1.getValue()); out.println("

Expiry date or age before setting: " + c1.getMaxAge()); c1.setMaxAge(2*60*60); // age is set with 2 hours (7200 seconds) out.println("
Expiry date or age after setting: " + c1.getMaxAge()); out.println("

Comment: " + c1.getComment()); out.println("
Path: " + c1.getPath()); out.println("
Version: " + c1.getVersion()); out.println("
Secure: " + c1.getSecure()); out.println("
Domain: " + c1.getDomain()+"
"); out.close(); } }

The meaning of methods is well discussed in the above API.

HTML file with submit button


Servlet Cookie


Servlet Cookie
Servlet Cookie methods screen when the user clicked submit button

6 thoughts on “Java Servlet Cookie API Methods”

  1. Thanks a lot sir
    You are explaining the concepts very well . Just remove all my previous comments and i think this modification will be more good .
    The Cookie is carried implicitly in request header from client to server which contains information like name, path, host and connection type etc. and the combination of this information is used by server to know cookie is coming from which client.

    1. After running the shopping cart example and add an item and then if we execute the getHeaderNames(); method
      we can see additional cookie row added in request header .

      So cookie is added inside the request header from client to server .

  2. Dear sir .

    In the following section How Servlet Cookie stored on the client are recognized by the server later?

    Here there is a small modification . Please replace “server” with “client” in the below statement

    “The Cookie carries implicitly (as response header) the server information like name, path, host and connection type etc.”

Leave a Comment

Your email address will not be published.