Java Web Application “Event Listener for Expired Sessions”

时光总嘲笑我的痴心妄想 提交于 2021-01-27 19:31:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/62576658/java-web-application-event-listener-for-expired-sessions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!