How to delete a cookie on server in a J2EE application

There is no direct method offered by servlet API to delete a cookie on server side. This is how you can go about doing it.

also read:

  1. Loop through the cookies in the request object to locate the one that you want to delete.
    for (Cookie cookie: request.getCookies()) {
        if (USER_COOKIE_NAME.equals(cookie.getName())) {
             return cookie;
        }
    }
  2. Set the maxAge property of the cookie to 0. This results in cookie expiring with immediate effect as soon as the client receives the response.
  3. Optionally, set the value property to empty string. This is not really required since the cookie is about to be expired. However, this adds a sense of a clean and complete erasure if the cookie being deleted carries some critical, secure data.
  4. Add this cookie to response. The cookie will be gone once the response is sent back to client!
    view plaincopy to clipboardprint
    cookie.setMaxAge(0);
    cookie.setValue("");
    response.addCookie(cookie);

 

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Trackbacks

  1. […] HTML5, client-side storage for web applications is limited to the tiny storage provided by cookies (4KB per cookie, 20 cookies per domain). In contrast, HTML5 storage provides a much larger initial […]

Speak Your Mind

*