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.

Example

 Live Demo

<html>
   <head>
      <title>Reading Cookies</title>
   </head>
   <body>
      <center>
         <h1>Reading Cookies</h1>
      </center>
      <%
         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 ) {
                  cookie.setMaxAge(0);
                  response.addCookie(cookie);
                  out.print("Deleted cookie: " +
                  cookie.getName( ) + "<br/>");
               }
               out.print("Name : " + cookie.getName( ) + ", ");
               out.print("Value: " + cookie.getValue( )+" <br/>");
            }
         } else {
            out.println(
            "<h2>No cookies founds</h2>");
         }
      %>
   </body>
</html>

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

Output

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.

raja
Published on 22-Mar-2019 05:32:26
Advertisements