Java Web 应用程序“过期会话的事件侦听器" [英] Java Web Application "Event Listener for Expired Sessions"

查看:27
本文介绍了Java Web 应用程序“过期会话的事件侦听器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 HttpServletRequest Session 过期后运行 Java 代码?

Is there a way to run Java code, after a HttpServletRequest Session expired?

如果会话过期,我需要进行数据库调用.

If a Session expires, I need to make a DB call.

回调和监听器将可用.

推荐答案

javax.servlet.http.HttpSessionListener

Jakarta Servlet 规范为会话过期提供了一个侦听器接口: HttpSessionListener.

您编写一个类来实现该接口上的两个方法.使用注释标记您的类 @WebListener 让您的servlet容器自动实例化您的类.当会话过期时,servlet 容器会自动调用 sessionDestroyed 类实例上的方法.

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.

在那里 sessionDestroyed 方法,您可以执行您想要的任何操作,例如写入数据库.

There in that sessionDestroyed method, you can take any actions you want such as writing to your database.

Jakarta Servlet 规范提供了其他几个这样的侦听器接口.您可以看到它们列在 @WebListener 注释的 Javadoc.

The Jakarta Servlet spec provides several other such listener interfaces. You can see them listed on that @WebListener annotation’s Javadoc.

特别是ServletContextListener 为您提供有关 Web 应用程序(servlet 语言中的上下文")何时启动以及 Web 应用程序何时关闭的挂钩.因此,您可以执行应用程序范围的设置和拆卸操作.这些操作将在您在实现该接口的类中编写的两个方法中进行.

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.

这篇关于Java Web 应用程序“过期会话的事件侦听器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆