如何删除域下不同路径的所有cookie

时间:2018-06-04 07:23:22

标签: java spring-mvc jsp servlets cookies

Cookie [] cookies = request.getCookies();

for(Cookie cookie:cookies)
{
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie); 
}

我使用此代码删除浏览器中的所有Cookie,某些路径(“/”)设置为null的Cookie也会过期,但它也会过期,但某些路径(/ xyz)的Cookie无法获取变化

当用户从我的应用程序退出时,请帮我从浏览器中删除所有Cookie。

1 个答案:

答案 0 :(得分:0)

这可能会对你有帮助。

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookiesUtil {

  public static final int COOKIE_DEFAULT_AGE = 30 * 24 * 60 * 60; // 30天
  private static final String COOKIE_DOMAIN = ".domain.com";
  private static final String COOKIE_PATH = "/";

  public static void removeCookie(String cookieName, HttpServletResponse response) {
    removeCookie(cookieName, COOKIE_DOMAIN, COOKIE_PATH, response);
  }

  /**
   * remove cookie
   * @param cookieName
   * @param domain
   * @param response
   */
  private static void removeCookie(String cookieName, String domain,
      String path, HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName, "");
    cookie.setPath(path);
    cookie.setDomain(domain);
    cookie.setMaxAge(0);
    response.addCookie(cookie);
  }
}