Friday, April 26, 2013

deleting browser cookies (in java)

In our implementation, there's a need for a session cookie that will be created during the user login and that should be deleted during the logout. Everything I read on Google tell the same thing:
  1. Get the cookie object from the request
  2. Set its max age to 0
  3. Add the cookie to the response
This should be quite simple right? But I still see my cookie even if I implement these steps.
After a little bit of search and a little try, I see that I must set cookie path as "/" as well. So the result code is as below. getCookie() takes the cookie from the request object, and deleteCookie() deletes it.

01public Cookie getCookie(HttpServletRequest request, String cookieName) {
02 if (request != null && cookieName != null) {
03  Cookie[] cookies = request.getCookies();
04  if (cookies != null) {
05   for (Cookie cookie : cookies) {
06    if (cookieName.equals(cookie.getName())) {
07     return cookie;
08    }
09   }
10  }
11 }
12 return null;
13}
14 
15public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
16 Cookie cookie = getCookie(request, cookieName);
17 if (cookie != null) {
18  cookie.setMaxAge(0);
19  cookie.setPath("/");
20 }
21 response.addCookie(cookie);
22}