views:

32

answers:

2

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.

+2  A: 

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.

BalusC
The problem was that I tried to change a cookie with the path "/admin" and my servlets path is "/admin/". is it not possible to remove a cookie on another path or another domain?
Stefan
You can remove a cookie on another path of the same domain. You just have to set its maxage to 0. You should not change the path. It would only create a new cookie (which in turn would immediately disappear because maxage is 0). You cannot access cookies on another domain. This is a security restriction. You can at highest access cookies of another subdomain. You only need to set domain as `.example.com` instead of `example.com`.
BalusC
A: 

The problem was that the cookie I wanted to remove had a path that was "/admin" and my logout servlet had the path "/admin/logoutServlet". When I get the cookie from the request the path is set to null. So when I add the cookie the path is set to "/admin/" as my servletIf I created a cookie with the path "/admin/" the servlet was able to remove it.

I solved the problem by explisitly setting the path of the cookie before adding it to the response.

minIdCookie.setMaxAge(0);
minIdCookie.setPath("/");
res.addCookie(minIdCookie);

But I don't understand why the path is null.

Stefan