How to properly logout of a Java EE 6 Web Application after logging in

smagrath picture smagrath · Jun 5, 2012 · Viewed 27.5k times · Source

A pretty simple requirement. After logging into web J2EE 6 application, how can I have the user logout again?

Most (all?) the books and tutorials I have seen show how to add a login/loginerror page to their application and demonstrate the use of security principals/roles/realms etc using the "j_security_check" method - all good. But then it's not clear how to give the user the power to logout. Indeed, how can I force a logout after, say, the session times out, etc?

Answer

Ramesh PVK picture Ramesh PVK · Jun 5, 2012

You should have logout servlet/jsp which invalidates the session using the following ways:

  • Before Servlet 3.0, using session.invalidate() method which invalidates the session also.
  • Servlet 3.0 provides a API method HttpServletRequest.logout() which invalidates only the security context and the session still exists.

And, the Application UI should be providing a link which invokes that logout servlet/jsp

Question: Indeed, how can I force a logout after, say, the session times out, etc?

Answer: The <session-timeout> in web.xml lets you define the timeout value after which the session will get invalidated by the server.