Java – the problem of deleting cookies in servlets
•
Java
I try to use this code to delete cookies in the servlet
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 has no effect and does not change the cookie properties
I also try to add a cookie to this servlet, which works well
Why can't I change the properties of an existing cookie
Solution
You shouldn't change the path This will change the cookie identity If a cookie is set for a path such as / Foo and changed to /, the client will no longer associate the changed cookie with the original cookie Cookies are identified by name and path
Setting maxage to 0 should be sufficient
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 cookies are read / tested in subsequent new requests, not in the current request
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码