有没有办法在 Java/Tomcat/JSP web 项目中附加到像 asp.net 的“Application_Start”和“Begin_Request”这样的事件?我真的不想使用 JSF 或额外的框架(Spring、Struts)。我不想在每页的基础上使用“jspInit”之类的东西,目标是全局事件处理程序。
如果我坚持使用 .net 做事方式,关键是要有一个中心位置来初始化 IoC 容器 (Application_Start),并实现“每个请求一个数据库事务”工作流 (Begin_Request)。
谢谢。
最佳答案
在Java EE(Servlets+JSPs)的世界中,通过实现Java EE规范标准化的相关接口(interface)可以获得等价的功能。
应用程序概念的等价物是 Web 上下文或 Servlet 上下文。 session 和请求在 Java EE 中与 .Net 中的概念相同。有相关的监听器类需要实现才能 Hook 到
中的相关事件- 应用程序的生命周期(ServletContextListener 和ServletContextAttributeListener),
- 应用程序提供的请求(ServletRequestListener 和 ServletRequestAttributeListener)或
- session 由相同的(HttpSessionListener 和 HttpSessionActivationListener)建立。
有关这方面的更多信息,请参阅 Java EE 5 tutorial on the Servlet lifecycle .这些接口(interface)继续适用于 Java EE 6
过滤器与 ServletRequestListener
如果您阅读过评论,您会注意到可以通过实现 ServletRequestListener
来对请求进行预处理和后处理。或 Filter
.
我建议您使用 Filter
s(和 BalusC 一样)。这是因为 Filter
每次将请求发送到特定 URL 时都会调用,这通常是确保对 URL 的所有请求都接受相同“处理”的最有效方法。
原因可以在 ServletRequestListener
上的 Java EE API 文档中找到。 :
Interface for receiving notification events about requests coming into and going out of scope of a web application.
A ServletRequest is defined as coming into scope of a web application when it is about to enter the first servlet or filter of the web application, and as going out of scope as it exits the last servlet or the first filter in the chain.
当您使用 ServletRequestListener
,您必须注意,requestInitialized 和 requestDestroyed 事件仅在每个请求中触发一次(不同于 Filter
,其中 doFilter 方法每次都被调用Filter
在处理管道中调用)。由于过滤器是在请求前后执行操作的常用方式(我还没有看到很多人使用 ServletRequestListeners),我建议您在这种情况下使用过滤器。
关于java - 像 .net 的 "Application_Start"和 "Begin_Request"for java/tomcat/JSP 这样的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3663511/