aspose file tools*
The moose likes Servlets and the fly likes Notify ServletContext When a Session is Invalidated Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Notify ServletContext When a Session is Invalidated" Watch "Notify ServletContext When a Session is Invalidated" New topic
Author

Notify ServletContext When a Session is Invalidated

s_oscott
Greenhorn

Joined: Nov 16, 2001
Posts: 1
I'd like to keep track of the number of users logged in to my web app by keeping a counter as an attribute in the ServletContext. When a session is created, the counter would be incremented. When a session is invalidated (either by a timeout or by session.invalidate()), I'd like this counter to be decremented. I was planning to bind an object that is an HttpSessionBindingListener to each session and have it decrement the counter in the ServletContext when the session is invalidated, but I can't figure out a way to access the ServletContext from this object. Please let me know if there is an easier/better solution to this problem. BTW: I planned to use an attribute in the ServletContext as opposed to saving values to a database to avoid the database overhead.
Thank you!
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
You can make the ServletContext an attribute of the object you're binding. Of course, that won't work in a distributed environment, but hey, the entire scheme won't work in a distributed environment anyway.
If your container supports servlet 2.3 then you can simply use a HttpSessionListener. It is much simpler and non-invasive: you would set it up in the web.xml file without modifying any existing code.
- Peter
Sean MacLean
author
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
"s_oscott",
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please log in with a new name which meets the requirements.
Thanks.
Sean
 
Consider Paul's rocket mass heater.
 
subject: Notify ServletContext When a Session is Invalidated