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.

 public Cookie getCookie(HttpServletRequest request, String cookieName) {
  if (request != null && cookieName != null) {
   Cookie[] cookies = request.getCookies();
   if (cookies != null) {
    for (Cookie cookie : cookies) {
     if (cookieName.equals(cookie.getName())) {
      return cookie;
     }
    }
   }
  }
  return null;
 }

 public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
  Cookie cookie = getCookie(request, cookieName);
  if (cookie != null) {
   cookie.setMaxAge(0);
   cookie.setPath("/");
  }
  response.addCookie(cookie);
 }