Skip to main content
 首页 » 编程设计

servlets之从Servlet响应中删除cookie

2024年11月01日102lautakyan007

我想知道如何在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,但是它也不起作用。

请您参考如下方法:

将最大年龄设置为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有什么用。基本上,您还允许最终用户操纵其值(value)。而是将其存储为 session 属性,然后在注销时调用 session.invalidate()