DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

I am a Software Engineer and a keen enthusiast of Semantic Web technologies. I am a regular speaker at JUG Chennai and also have contributed to many open source projects. I am also the community lead of Lotico Semantic Web Chennai. Shiv Kumar has posted 9 posts at DZone. You can read more from them at their website. View Full User Profile

Destroy Cookie while Logging out.

08.15.2013
| 5298 views |
  • submit to reddit
@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);
		}
	}

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.

Comments

Vaibhav Gupta replied on Tue, 2013/11/05 - 3:32pm

 Will it work with facelets?