JSP Deleting cookies

We have already learnt about the basic concepts of the cookies and the way to set cookies and accessing the cookies. In this tutorial we will be learning, how to remove or delete the already created cookies ?

JSP Deleting cookies

<title>Reading Cookies</title>
   <h1>Reading Cookies</h1>
      Cookie cookie = null;
      Cookie[] cookies = null;

      cookies = request.getCookies();
      if (cookies != null) {
         out.println("<h2>List of Cookies :</h2>");
         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.print("Deleted cookie: " + cookie.getName());
            out.print("Name : " + cookie.getName());
            out.print("Value: " + cookie.getValue());
      } else {
         out.println("<h2>No cookies founds</h2>");

Output of the program :
deleting cookies in jsp

Explanation : JSP Deleting cookies

In the above example, We have deleted the cookies that has been already created by executing some JSP program. Now we also know the way to access those cookies using the getCookies() method.

Steps to delete the cookies :

In order to delete the cookies we need to execute following steps –

  1. Access the existing cookie
  2. Change the Maximum age of the cookie to zero
  3. Update the cookie object

Below 3 lines are doing exactly same work as mentioned in the above 3 steps –

cookie = cookies[i];        // Step 1
cookie.setMaxAge(0);        // Step 2
response.addCookie(cookie); // Step 3