posted 14 years ago
That's a bad idea.
HTTP doesn't work by opening a connection and holding it until the user logs out (or closes the browser). Instead, each time you send a URL, a connection is opened from the browser to the server, data is sent from the browser to the server, the server sends back a response, then the connection is closed. The rest of the time, the server doesn't even know the client is there, and the client can be communicating with completely different servers. In fact, that's what the HttpSession object is all about. To give the illusion of a continuous connection even though one doesn't physically exist.
In order to do "server stuff" when the browser closes, the act of closing the browser would have to open a connection, send a message to the indicated server, then process its response. And, of course, make the distinction between closing a browser window and closing the entire browser application.
While the days are gone when one of the most common ways to "close a browser" was to crash Windows, there's still no guarantee that you can catch a user in the act of disconnection. Plus, realize that most of us don't close a browser window when we exit an application, we simply move on to a different application, using the same browser window. Except that, unless we explicitly log out, we haven't really "exited" the webapp, since we can (and often we do) return to the application later, and, as long as the HttpSession hasn't timed out, we're still logged in.
In short, you can perform an action when a user's session times out, or when a user explictly logs out (assuming that they bother to do that), but expecting to tie an action to closing of browser windows isn't likely to work as well as you hoped. Plus, you'd actually have to make some sort of client-side customization to the browser to send/receive that final server request.
About the closest you can get is to do like certain apps and have a "don't close this window" window that does an AJAX request on a window-close event. Although I'm not a real big fan of that approach myself.
The secret of how to be miserable is to constantly expect things are going to happen the way that they are "supposed" to happen.
You can have faith, which carries the understanding that you may be disappointed. Then there's being a willfully-blind idiot, which virtually guarantees it.