cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.


How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

cookies in servlet


Types of Cookie

There are 2 types of cookies in servlets.

  1. Non-persistent cookie
  2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.


Advantage of Cookies

  1. Simplest technique of maintaining the state.
  2. Cookies are maintained at client side.

Disadvantage of Cookies

  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won’t work.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class

Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:

  1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
  2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

How to create Cookie?

Let’s see the simple code to create cookie.

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object  
response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let’s see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie  
ck.setMaxAge(0);//changing the maximum age to 0 seconds  
response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let’s see the simple code to get all the cookies.

Cookie ck[]=request.getCookies();  
for(int i=0;i<ck.length;i++){  
 out.print("
"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie  
}

Simple example of Servlet Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value.

cookies in session tracking

index.html

Name:

FirstServlet.java

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class FirstServlet extends HttpServlet {  
  
  public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String n=request.getParameter("userName");  
    out.print("Welcome "+n);  
  
    Cookie ck=new Cookie("uname",n);//creating cookie object  
    response.addCookie(ck);//adding cookie in the response  
  
    //creating submit button  
    out.print("");  
    out.print("");  
    out.print("");  
          
    out.close();  
  
        }catch(Exception e){System.out.println(e);}  
  }  
}

SecondServlet.java

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class SecondServlet extends HttpServlet {  
  
public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
      
    Cookie ck[]=request.getCookies();  
    out.print("Hello "+ck[0].getValue());  
  
    out.close();  
  
         }catch(Exception e){System.out.println(e);}  
    }  
      
  
}

web.xml

  
  
  
s1  
FirstServlet  
  
  
  
s1  
/servlet1  
  
  
  
s2  
SecondServlet  
  
  
  
s2  
/servlet2  
  
  

Output

servlet cookie servlet cookies servlet cookies example