Delete cookie from a servlet response

前端 未结 2 852
栀梦
栀梦 2020-12-08 10:20

I would like to know how to delete a cookie in an HttpServletResponse in Spring MVC. I have the login method where I create the cookie and the logout where I wa

相关标签:
2条回答
  • 2020-12-08 10:37

    No need to use your own code. Just configure rememberMeServices bean that would create cookie while user' logging in with rememberMe option checked, and would delete it after logout.

    0 讨论(0)
  • 2020-12-08 10:46

    Setting the maximum age to 0 is right. But it must have exactly the same other cookie properties, except of the value. Thus exactly the same domain, path, secure, etc. The value is optional, it can best be set to null.

    So, given the way how you created the cookie,

    Cookie cookie = new Cookie("user", user);
    cookie.setPath("/MyApplication");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(3600);
    response.addCookie(cookie);
    

    it needs to be removed as follows:

    Cookie cookie = new Cookie("user", null); // Not necessary, but saves bandwidth.
    cookie.setPath("/MyApplication");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(0); // Don't set to -1 or it will become a session cookie!
    response.addCookie(cookie);
    

    That said, I'm not sure how it's useful to store the logged-in user as a cookie. You're basically also allowing the enduser to manipulate its value. Rather just store it as a session attribute instead and call session.invalidate() on logout.

    0 讨论(0)
提交回复
热议问题