Reputation: 1179
Is there a way to run Java code, after a HttpServletRequest Session
expired?
If a Session expires, I need to make a DB call.
Callback and Listener would be useable.
Upvotes: 2
Views: 792
Reputation: 338231
javax.servlet.http.HttpSessionListener
The Jakarta Servlet specification provides a listener interface for session expiring: HttpSessionListener
.
You write a class that implements the two methods on that interface. Mark your class with the annotation @WebListener
to have your class automatically instantiated by your servlet container. When a session expires, the servlet container automatically invokes the sessionDestroyed
method on the instance of your class.
There in that sessionDestroyed
method, you can take any actions you want such as writing to your database.
The Jakarta Servlet spec provides several other such listener interfaces. You can see them listed on that @WebListener
annotation’s Javadoc.
In particular, ServletContextListener
gives you hooks for when your web app (a “context” in servlet-speak) is launching, and when your web app is shutting down. So you can perform app-wide setup and teardown operations. Those operations would go in the two methods you write in a class implementing that interface.
Upvotes: 2