posted 13 years ago
Sessions are not expired from application code.
Sessions are expired by the Container (the webapp server). Expiration is done when the container notices that a session has not been referenced within the session timeout period, defined by default by the container and customizable on a per-application basis in web.xml.
Sessions are kept alive by the simple process of making an HTTP request to the webapp with that session ID. That is why the session never expires when periodic AJAX polling is done. Each poll results in an HTTP request, and each HTTP request causes the container to reset the session countdown timer.
Session-related activity is solely concerned with HTTP requests and webapp HTTP request processors are not continuously-executing processes. Therefore you cannot take action when a session actually expires, only see when a request has been made after a session has expired. This can be assisted somewhat by implementing Session Listeners, but session listener events aren''t guaranteed to happen exactly at the instant of timeout, only at some convenient time after the timeout. Convenient to the container, that is.
On the other hand, what you're probably looking to do is timeout and logout a user and the AJAX polling is interfering with that. What you can do is maintain a user-time timer of your own and ONLY reset it when you handle normal page requests, but not AJAX requests. Then, when a page request comes in, if the user-time timer has expired, manually invalidate the session, which effectively logs the user out. A refinement of that concept that's even better is to place code on the web pages that is sensitive to an AJAX response with a "user timed out" status and use that to trigger a page reload to display a "You have just been logged out" page, rather than waiting for an actual new full-page user request.
Trying to separate the timeout and non-timeout (AJAX) requests can be troublesome, since it's a cross-cutting concern and not something that you want to have people to have to remember to manually code into every eligible HTTP request handler. Sooner or later, someone will forget to do so.
To avoid that problem, you might prefer to setup a URL formulation that clearly distinguishes the AJAX URLs from the non-AJAX URLs and add a Session Filter that handles the user timer before the request is passed on to the regular application code.
Experience keeps a dear School, but Fools will learn in no other.
---
Benjamin Franklin - Postal official and Weather observer