Over a million developers have joined DZone.
Platinum Partner

Destroy Cookie while Logging out.

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix. Download this Forrester Report to gain a better understanding of the low-code platform market and how to make a strategic platform selection you won’t regret.

I was facing a problem where while a person logs out his session is invalidated but the JSESSIONID still remained in the browser. As a result while logging in the Java API used to get the request from the browser along with a JSESSIONID(Just the ID since the session was invalidated) and would create the new session with the same ID. To fix this problem I used the above code so that whenever a user logs out the entire JSESSIONID becomes empty and thus cookie wont exist for that site.Anyone using JAVA can utilize this in their code.

@RequestMapping(value = "/logout", method = RequestMethod.POST)
public void logout(HttpServletRequest request,
HttpServletResponse response) {
/* Getting session and then invalidating it */
HttpSession session = request.getSession(false);
if (request.isRequestedSessionIdValid() && session != null) {
session.invalidate();
}
handleLogOutResponse(response);
}

/**
 * This method would edit the cookie information and make JSESSIONID empty
 * while responding to logout. This would further help in order to. This would help
 * to avoid same cookie ID each time a person logs in
 * @param response
 */
private void handleLogOutResponse(HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie);
}
}

The Web Dev Zone is brought to you in partnership with Mendix. Better understand the aPaaS landscape and how the right platform can accelerate your software delivery cadence and capacity with the Gartner 2015 Magic Quadrant for Enterprise Application Platform as a Service.

Topics:
web dev

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}