Removing a Cookie
by Frank Kim on Feb.04, 2009, under Java
To remove a cookie the API suggests getting the cookie, setting its maxAge to 0, and then adding that cookie to the response. Digging around deeper I realized you also need to set the domain and the path. Here is an example of how to do this.
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals(COOKIE_WE_WANT)) {
cookie.setMaxAge(0);
cookie.setDomain(".betweengo.com");
cookie.setPath("/");
response.addCookie(cookie);
break;
}
}
It turns out though the catch is making sure that by the time you add the cookie to the response that the response has not already been committed. Previously the above code was in a tag but that was too late to modify the response. I moved this code to a filter and then it worked fine.
No related posts.