从servlet响应中删除cookie

Cru*_*ruz 25 cookies servlets spring-mvc

我想知道如何删除HttpServletResponseSpring 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");
 }
Run Code Online (Sandbox Code Playgroud)

我认为只需要更改maxAge,但在浏览器中cookie不会改变.我甚至尝试在注释块中重写一个具有相同名称的cookie,但它也不起作用.

Bal*_*usC 77

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

那么,考虑到你创建cookie的方式,

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

它需要删除如下:

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);
Run Code Online (Sandbox Code Playgroud)

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