title: How do you remove a Cookie in a Java Servlet
body: <p>How do you remove a cookie in a Java servlet?</p>
  
  <p>I tried this:
  <a href="http://www.jguru.com/faq/view.jsp?EID=42225" rel="noreferrer">http://www.jguru.com/faq/view.jsp?EID=42225</a></p>
  
  <p>EDIT: The following now works successfully it appears to be the combination of:</p>
  
  <pre><code>response.setContentType("text/html");
  </code></pre>
  
  <p>and</p>
  
  <pre><code>cookie.setMaxAge(0);
  </code></pre>
  
  <p>Before I was doing:</p>
  
  <pre><code>//remove single signon cookie if it hasn't been validated yet
  response.setContentType("text/html");
  Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
  cookie.setDomain(SSORealm.SSO_DOMAIN);
  cookie.setMaxAge(-1);
  cookie.setPath("/");
  cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
  response.addCookie(cookie);
  </code></pre>
  
  <p>Which expires the cookie when the browser is closed as per <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/Cookie.html#setMaxAge%28int%29" rel="noreferrer">the documentation</a>.</p>
  
  <blockquote>
    <p>A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted. </p>
  </blockquote>
  
  <p>The full working snippet to expire a cookie is:</p>
  
  <pre><code>//remove single signon cookie if it hasn't been validated yet
  response.setContentType("text/html");
  Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
  cookie.setDomain(SSORealm.SSO_DOMAIN);
  cookie.setMaxAge(0);
  cookie.setPath("/");
  cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
  response.addCookie(cookie);
  </code></pre>