Reputation: 1951
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.
Upvotes: 5
Views: 9141
Reputation: 44814
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
Upvotes: 7
Reputation:
Where are you redirecting? The response has to be committed back to the host that created the cookie in the first place in order for it to be removed. Also, you don't need to set the value to null.
Upvotes: 0