Java:Why http session is not destroyed when tab or browser is closed

javasession

I have the following implementation of HttpSessionlistener

public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener {


public void attributeAdded(HttpSessionBindingEvent event) {
   ...

}


public void attributeRemoved(HttpSessionBindingEvent event) {

    ...
}

public void attributeReplaced(HttpSessionBindingEvent event) {

}

//HttpSesion creation & destruction
public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    //log created time


}

public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    long destroyedTime = System.currentTimeMillis();
    //log destroyed time

}

}

Basically i log the session creation and destruction time.
But if the session is long (default to 30 minutes), and user closes browser meanwhile, the

sessionDestroyed 

is not called ?

Why is that ?
Is there a workaround to log exactly the when the session was destroyed (when user closes the browser)? Should'nt be this be the browser's problem, to kill the session when it is closed ?

Is there any interface that i have to implement for this to work ?

Thank you !

Best Answer

How would the server know when the browser is closed or the tab closed? At that point the browser doesn't send anything to the server.

This is a fundamental part of HTTP - it's a request/response protocol, not a "permanently open conversation" where you can tell if one party leaves the conversation. Think of it as a series of telegrams rather than a phone call - and you can't tell when you've received the last telegram you're going to get.

You'll need to design your way round this - to avoid needing to know when the browser has been closed. There are some ugly hacks to work around it - making AJAX poll the server with a heartbeat message, for example - but changing the design is a better solution.

Related Topic