This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
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

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Notify ServletContext When a Session is Invalidated" Watch "Notify ServletContext When a Session is Invalidated" New topic

Notify ServletContext When a Session is Invalidated


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
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
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at . 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.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Notify ServletContext When a Session is Invalidated
It's not a secret anymore!