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!
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
"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
subject: Notify ServletContext When a Session is Invalidated