Javax.servlet.http.Cookie class in Java

Many websites use small strings of text known as cookies to store persistent client-side state between connections. Cookies are passed from server to client and back again in the HTTP headers of requests and responses. Cookies can be used by a server to indicate session IDs, shopping cart contents, login credentials, user preferences, and more.

How Cookies work?

How cookies work?

As seen from the above diagram, when a user first request for a page, the server along with the resource sends a cookie object to be stored on the client’s machine. This object might contain details of the request. Now later, if the user again requests for the same resource, it sends along with the request the cookie stored which can be used by servers to further enhance the experience of the user.

Attributes of Cookie :

  • Name = value pair: This depicts the actual information stored within the cookie. Neither the name nor the value should contain white space or any of the following characters: [ ] ( ) = , ” / ? @ : ;
    Example of valid cookie name-value pair:

     Set-Cookie:session-id = 187-4969589-3049309
  • Domain: By default, a cookie applies to the server it came from. If a cookie is originally set by, the browser will only send the cookie back to However, a site can also indicate that a cookie applies within an entire subdomain, not just at the original server. For example, this request sets a user cookie for the entire domain:
    The browser will echo this cookie back not just to, but also to,,, and any other host somewhere in the domain. However, a server can only set cookies for domains it immediately belongs to. cannot set a cookie for,, or .com, no matter how it sets the domain.

     Set-Cookie: user = geek ;Domain
  • Path: When requesting a document in the subtree from the same server, the client echoes that cookie back. However, it does not use the cookie in other directories on the site.
    Set-Cookie: user = geek; Path =/ restricted
  • Expires : The browser should remove the cookie from its cache after that date has passed.
     Set-Cookie: user = geek; expires = Wed, 21-Feb-2017 15:23:00 IST
  • Max-Age : This attribute sets the cookie to expire after a certain number of seconds have passed instead of at a specific moment. For instance, this cookie expires one hour (3,600 seconds) after it’s first set.
    Set-Cookie: user = "geek"; Max-Age = 3600

Constructor : Creates a cookie with specified name-value pair.

Syntax : public Cookie(String name, String value)
Parameters :
name : name of the cookie
value : value associated with this cookie

Methods :

  1. setDomain() : Sets the domain in which this cookie is visible. Domains are explained in detail in the attributes of cookie part previously.
    Syntax : public void setDomain(String pattern)
    Parameters :
    pattern : string representing the domain in which this cookie is visible.
  2. getDomain() : Returns the domain in which this cookie is visible.
    Syntax : public String getDomain()
  3. setComment() : Specifies the purpose of this cookie.
    Syntax : public void setComment(String purpose)
    Parameters :
    purpose : string representing the purpose of this cookie.
  4. getComment() : Returns the string representing purpose of this cookie.
    Syntax : public String getComment()
  5. setMaxAge() : Specifies the time (in seconds) elapsed before this cookie expires.
    Syntax : public void setMaxAge(long time)
    Parameters :
    time : time in seconds before this cookie expires
  6. getMaxAge() : Returns the max age component of this cookie.
    Syntax : public String getMaxAge()
  7. setPath() : Specifies a path for the cookie to which the client should return the cookie.
    Syntax : public void setPath(String path)
    Parameters :
    path : path where this cookie is returned
  8. getPath() : Returns the path component of this cookie.
    Syntax : public String getMaxAge()
  9. setSecure() : Indicated if secure protocol to be used while sending this cookie. Default value is false.
    Syntax : public void setSecure(boolean secure)
    secure - If true, the cookie can only be sent over a secure
    protocol like https. 
    If false, it can be sent over any protocol.
  10. getSecure() : Returns true if this cookie must be
    sent by a secure protocol, otherwise false.

    Syntax : public boolean getSecure()
  11. getName() : Returns the name of the cookie.
     Syntax : public String getName()
  12. setValue() : Assigns new value to cookie after initialisation.
    Syntax : public void setValue(String newValue)
    Parameters :
    newValue - a String specifying the new value
  13. getValue : Returns the value of the cookie.
    Syntax : public String getValue()
  14. getVersion() : Returns 0 if the cookie complies with the original Netscape specification; 1 if the cookie complies with RFC 2965/2109
    Syntax : public int getVersion()
  15. setVersion() : Used to set the version of the cookie protocol this cookie uses.
    Syntax :public void setVersion(int v)
    Parameters :
    v - 0 for original Netscape specification; 1 for RFC 2965/2109
  16. clone() : returns a copy of this cookie.
    Syntax : public Cookie clone()

Below is a Java implementation of a simple servlet program which stores a cookie in the browser when user first requests for it and then for further requests it displays the cookies stored.





// Java program to illustrate methods
// of Cookie class
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 * Servlet implementation class cookieTest
public class cookieTest extends HttpServlet 
    private static final long serialVersionUID = 1L;
     * @see HttpServlet#HttpServlet()
    public cookieTest() {
        // TODO Auto-generated constructor stub
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
        // Create a new cookie with the name test cookie
        // and value 123
        Cookie cookie = new Cookie("test_cookie", "123");
        // setComment() method
        cookie.setComment("Just for testing");
        // setDomain() method
        // cookie.setDomain("domain");
        // setMaxAge() method
        // setPath() method
        // setSecure() method
        // setValue() method
        // setVersion() method
        PrintWriter pw = response.getWriter();
        Cookie ck[] = request.getCookies();
        if (ck == null) {
            pw.print("<p>This is first time the page is requested.</p>");
            pw.print("<p>And therefore no cookies found</p></body></html>");
        } else {
            pw.print("<p>Welcome Again...Cookies found</p>");
            for (int i = 0; i < ck.length; i++) {
                // getName() method
                pw.print("<p>Name :" + ck[i].getName() + "</p>");
                // getValue() method
                pw.print("<p>Value :" + ck[i].getValue() + "</p>");
                // getDomain() method
                pw.print("<p>Domain :" + ck[i].getDomain() + "</p>");
                // getPath() method
                pw.print("<p>Name :" + ck[i].getPath() + "</p>");
                // getMaxAge() method
                pw.print("<p>Max Age :" + ck[i].getMaxAge() + "</p>");
                // getComment() method
                pw.print("<p>Comment :" + ck[i].getComment() + "</p>");
                // getSecure() method
                pw.print("<p>Name :" + ck[i].getSecure() + "</p>");
                // getVersion() method
                pw.print("<p>Version :" + ck[i].getVersion() + "</p>");
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
        doGet(request, response);


OUTPUT: The following output are from a web browser-
For the first request:

This is first time the page is requested.
And therefore no cookies found.

For the second request:

Welcome Again...Cookies found
Name :test_cookie
Value :321
Domain :null
Name :null
Max Age :-1
Comment :null
Name :false
Version :0

How to run the above program?

First, make sure you have some server like Apache Tomcat installed and is configured with the tool you are using like Eclipse. Simply run the above program on the server or on your local browser by putting the full address of the server directory you are using.
The CookieTest servlet, a servlet that performs three tasks:

  1. First, the servlet sets a cookie with the name test_cookie. Other lines in the program set the attributes of the cookie such as max age, domain, value, etc.
  2. Second, the servlet uses request.getCookies to find all the incoming cookies and display their names and other corresponding attributes.
  3. If no cookies are found as is the case with the first request, a simple display message is displayed which tells that it is the first visit to the page.

Reference: Official Java Documentation

This article is contributed by Shaksham Garg and Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Improved By : Akanksha_Rai

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.