How to delete cookies with JSP?

To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow these three steps −

  • Read an already existing cookie and store it in Cookie object.

  • Set cookie age as zero using the setMaxAge() method to delete an existing cookie.

  • Add this cookie back into the response header.

Following example will show you how to delete an existing cookie named "first_name" and when you run main.jsp JSP next time, it will return null value for first_name.


 Live Demo

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

         // Get an array of Cookies associated with the this domain
         cookies = request.getCookies();

         if( cookies != null ) {
            out.println("<h2> Found Cookies Name and Value</h2>");
            for (int i = 0; i < cookies.length; i++) {
               cookie = cookies[i];
               if((cookie.getName( )).compareTo("first_name") == 0 ) {
                  out.print("Deleted cookie: " +
                  cookie.getName( ) + "<br/>");
               out.print("Name : " + cookie.getName( ) + ", ");
               out.print("Value: " + cookie.getValue( )+" <br/>");
         } else {
            "<h2>No cookies founds</h2>");

Let us now put the above code in the main.jsp file and try to access it. It will display the following result −


Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player

Now run http://localhost:8080/main.jsp  once again and it should display only one cookie as follows −

Found Cookies Name and Value
Name : last_name, Value: Player

You can delete your cookies in the Internet Explorer manually. Start at the Tools menu and select the Internet Options. To delete all cookies, click the Delete Cookies button.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started