I'm having an issue with deleting cookies from my servlet code. Given bellow is my code.
private void clearCookies(HttpServletRequest req, HttpServletResponse resp) {
Cookie[] cookies = req.getCookies();
for (Cookie curCookie : cookies) {
curCookie.setValue(null);
curCookie.setMaxAge(0);
curCookie.setPath("/");
resp.addCookie(curCookie);
}
}
I do a resp.sendRedirect(url) after this method call. However, not all cookies get deleted, for example this cookie never get deleted.
Name: reqURI
Content: ../../webapp/index.jsp
Domain: mgt.appserver.com
Path: /
Send for: Any kind of connection
Accessible to script: Yes
Created: Tuesday, November 26, 2013 4:35:19 PM
Expires: When the browsing session ends
Does anyone knows what I'm missing here? I read the Java Cookie object documentation and according to that value 0 should make the cookie to be removed. But it's not. And I tried many more suggestions and none of it worked. I tried this with Google Chrome and Firefox, so can't believe it's an issue with the browsers. I have no idea why such a generic thing is not properly documented and complected in a language like Java.
Moreover, if you try to remove the Google services cookies, the browser will automatically re-create them, making it impossible to remove data stored on Google servers. Thankfully, you can fix it by logging out of the Google services and then clearing out the browser history.
Google chrome has a cap on the number of cookies it allowed per domain . Once the total number of cookies in that domain exceeds that count, it deletes cookies!
To delete a cookie, set the Max-Age directive to 0 and unset its value. You must also pass the same other cookie properties you used to set it. Don't set the Max-Age directive value to -1 . Otherwise, it will be treated as a session cookie by the browser.
Update
As per Problem removing cookie in servlet
The path and domain will always be null when you retrieve cookies in Java because they are only necessary in the response for the client browser. However, if you're in the same security domain (regardless of the path), you still have the rights to delete them. Unfortunately, because the path is not included you can't delete the cookie now without explicitly knowing that path. Simply using the same cookie name, but a different path will not work. Those are considered two different cookies, and you will find that instead of deleting the cookie, you just created another one on a different path.
So you should not change value or path as this will create a new cookie
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