I trying to remove a cookie in a servlet with this code
Cookie minIdCookie = null;
for (Cookie c : req.getCookies()) {
if (c.getName().equals("iPlanetDirectoryPro")) {
minIdCookie = c;
break;
}
}
if (minIdCookie != null) {
minIdCookie.setMaxAge(0);
minIdCookie.setValue("");
minIdCookie.setPath("/");
res.addCookie(minIdCookie);
}
res.flushBuffer();
But this gives no effect and no change in the cookie properties.
I've also tried adding a cookie in this servlet and this works fine.
Why is it that I can not change the properties of an existing cookie.
To make a cookie, create an object of Cookie class and pass a name and its value. To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface. To fetch the cookie, getCookies() method of Request Interface is used.
Deleting a Cookie To delete a cookie, you need to create a new instance of the Cookie class with the same name and the Max-Age directive to 0 , and add it again to the response as shown below: // create a cookie Cookie cookie = new Cookie("username", null); cookie. setMaxAge(0); cookie.
There are two types of cookies in the servlet, these are Non-persistent, and persistent cookies.
You should not change the path. This would change the cookie identity. If the cookie were set for a path like /foo
and you change this to /
, then the client won't associate the changed cookie with the original cookie anymore. A cookie is identified by the name and the path.
Just setting maxage to 0 ought to be enough.
Cookie[] cookies = request.getCookies();
if (cookies != null) { // Yes, this can return null! The for loop would otherwise throw NPE.
for (Cookie cookie : cookies) {
if (cookie.getName().equals("iPlanetDirectoryPro")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
break;
}
}
}
You also need to ensure that you're reading/testing the cookie in the subsequent new request, not in the current request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With