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 want to delete it, but it doesn't work.
Here is the code:
@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"); }
I thought it was only needed to change the maxAge
, but in the browser the cookie don't change. I even tried to rewrite a cookie with the same name in the commented block but it doesn't work either.
Deleting a Cookie To delete a cookie, you need to create a new instance of the Cookie class with the same name and the Max-Age directive to 0 , and add it again to the response as shown below: // create a cookie Cookie cookie = new Cookie("username", null); cookie. setMaxAge(0); cookie.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With