从Servlet响应中删除cookie


问题内容

我想知道如何HttpServletResponse在Spring MVC中删除Cookie
。我在创建cookie的地方有登录方法,在要删除它的地方有注销方法,但是它不起作用。

这是代码:

@RequestMapping(method = RequestMethod.POST)
public ModelAndView Login(HttpServletResponse response, String user, String pass) {     
    if (user != null && pass != null && userMapper.Users.get(user).getPass().equals(pass)){
        Cookie cookie = new Cookie("user", user);
        cookie.setPath("/MyApplication");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
        Map model = new HashMap();
        model.put("user", user);
        return new ModelAndView("home", "model", model);
    }
    return new ModelAndView("login");
}

@RequestMapping(value="/logout", method = RequestMethod.POST)
public ModelAndView Logout(HttpServletRequest request, HttpServletResponse response) {

        Cookie[] cookies = request.getCookies();
        for(int i = 0; i< cookies.length ; ++i){
            if(cookies[i].getName().equals("user")){
                //Cookie cookie = new Cookie("user", cookies[i].getValue());
                //cookie.setMaxAge(0);
                //response.addCookie(cookie);
                cookies[i].setMaxAge(0);
                response.addCookie(cookies[i]);
                break;
            }
        } 
        return new ModelAndView("login");
 }

我以为只需要更改maxAge,但在浏览器中Cookie不会更改。我什至尝试在带注释的块中重写具有相同名称的cookie,但它也不起作用。


问题答案:

将最大年龄设置0为正确。但是,除了值外,它还必须具有 完全相同
的其他cookie属性。因此,域,路径,安全性等完全相同。该值是可选的,最好将其设置为null

因此,按照您创建Cookie的方式,

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

需要将其删除,如下所示:

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);

就是说,我不确定将登录用户存储为cookie有什么用。基本上,您还允许最终用户操纵其价值。而是将其存储为会话属性,然后session.invalidate()在注销时调用。