从servlet响应中删除cookie

时间:2012-03-22 12:05:15

标签: servlets cookies spring-mvc

我想知道如何在Spring MVC中删除HttpServletResponse中的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,但它也不起作用。

2 个答案:

答案 0 :(得分:74)

将最长年龄设置为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()

答案 1 :(得分:-1)

无需使用自己的代码。只需配置rememberMeServices bean,它将在用户使用rememberMe选项登录时创建cookie,并在注销后将其删除。