Remove cookies from a request while logging out – Java
Learn how to remove cookies from a request while logging out from a website/application.
Session cookies store information related to the user and other data related to the user when a user logs into a website or in these days, on visiting a website.
Let’s say you have a cookie called Session in your request, to invalidate it you need to empty its value, path and its max age.
cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie);
And add it to the response, of course. Otherwise the cookie would still remain active in the request.
The full code would look like..
Cookie[] cookies = request.getCookies(); if (cookies != null) for (Cookie cookie : cookies) { if ("Session".equals(cookie.getName())) { System.out.println("LOGGIN OUT ! Session cookie found.. Removing it !"); cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } }