giozh
giozh

Reputation: 10068

way to delete cookie

I have a questione about how to delete a cookie from a servlet. Let's presume that client has already a cookie sent by my servlet, one solution to delete it is to set the max age of cookie to 0. But what's the difference to set it like:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("cookie_name")) {
            cookies[i].setMaxAge(0);
            response.addCookie(cookies[i]);
        }
    }
}

or sent a new cookie and overwrite the old one like

Cookie myCookie = new Cookie("cookie_name", "");
response.addCookie(myCookie);

? and the cookie will be deleted immediatly or not?

Upvotes: 0

Views: 195

Answers (2)

BalusC
BalusC

Reputation: 1109635

The difference is that the first way checks if the cookie exists in client and then delete it, and that the second way outright deletes the cookie without checking if it exists in client. Makes logically sense, right? Ultimately, they have both the same effect: telling the browser to remove the cookie associated with the given name (and path).

You seem to be somehow assuming that the Cookie instance returned by getCookies() represents the actual cookie as the browser itself is using and that you have to use exactly that cookie instance in order to be able to delete it. This assumption is utterly wrong. It's just an abstraction of the cookie sent by the browser in the request headers. You can perfectly create a new Cookie instance, as long as it's using exactly the same name and path.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122026

AFAIAK,There is no evidence that the method addCookie won't check for the duplicates cookies.

It is up to you that to delete your cookie,before setting a new one, other wise you application the behavior is undefined.

It's better to delete.

Upvotes: 0

Related Questions