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 ?
<html> <head> <title>Reading Cookies</title> </head> <body> <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]; cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie: " + cookie.getName()); out.print("Name : " + cookie.getName()); out.print("Value: " + cookie.getValue()); } } else { out.println("<h2>No cookies founds</h2>"); } %> </body> </html>
Output of the program :
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.
In order to delete the cookies we need to execute following steps -
- Access the existing cookie
- Change the Maximum age of the cookie to zero
- 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