Web applications are normally configured to timeout sessions if they remain inactive for certain amount of time e.g. 30 minutes. This is normally setup in web.xml file by defining <session-config> element.
Sometimes a session becomes orphaned if the user does not logout properly and either closes the browser or opens a different url in the same window. To explicitly invalidate these sessions earlier rather than waiting for 30 minutes, you can use following technique.
Define a java class named "com.myco.bean.SessionBean" as follows:
In this class, we've defined one variable named "tracker" and two methods "onLoad" and "onUnload". onLoad method increments the tracker value by 1 and onUnload decrements the value by 1 and sleeps for 10 seconds. After 10 seconds, if the tracker value remains 0, the session is treated as orphaned and invalidated.
Define a rule in vroom-config.xml file as follows:
In the rule just note that we've bound the onload and onunload events of document object with SessionBean's onLoad and onUnload methods.
Let's say we've page1.jsp, page2.jsp and page3.jsp in our application. When the user opens page1.jsp, the value of tracker becomes 1 because onLoad method gets called. Now the user opens page2.jsp on a different tab, the value of tracker becomes 2 because tabs in browsers usually share a single session. If user loads page3.jsp in tab which was displaying page1.jsp, onUnload method gets called because page1.jsp is going to unload so the tracker value becomes 1 and the thread sleeps for 10 seconds. Meanwhile page3.jsp is loaded and tracker again becomes 2. When the thread wakes up the value of tracker remains 2 so session remains valid. Now user closes the browser and onUnload method gets called for both page2.jsp and page3.jsp. The tracker's value becomes 0. After 10 seconds when the thread wakes up, the value of tracker remains 0 so the session is invalidated.
This helps web application not to have orphaned sessions at all and to make the application more efficient and resource optimized.