Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem removing cookie in servlet

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.

like image 483
Stefan Rasmusson Avatar asked Aug 12 '10 09:08

Stefan Rasmusson


People also ask

How will you handle cookies in servlet?

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.

How do you remove cookies from a spring boot?

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.

How many types of cookies are in servlets?

There are two types of cookies in the servlet, these are Non-persistent, and persistent cookies.


1 Answers

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.

like image 175
BalusC Avatar answered Oct 23 '22 15:10

BalusC