web.xml中的load-on-startup是否可以用于在启动时加载任意类? [英] Can load-on-startup in web.xml be used to load an arbitrary class on startup?
问题描述
如何在Tomcat启动时加载任意类?
我看到了web.xml
文件的load-on-startup
标记,但是可以使用它吗,应该如何实现我的课程?
How can I load an arbitrary class on startup in Tomcat?
I saw load-on-startup
tag for web.xml
file, but can I use it and how should I implement my class?
<servlet-name>??</servlet-name>
<servlet-class>??</servlet-class>
<load-on-startup>10</load-on-startup>
推荐答案
用于指定servlet的加载顺序.但是,当您听起来更想寻找与Webapp启动有关的信息时,servlet更适合控制,预处理和/或后处理HTTP请求/响应.在这种情况下,您宁愿使用ServletContextListener
.
Those are meant to specify the loading order for servlets. However, servlets are more meant to control, preprocess and/or postprocess HTTP requests/responses while you sound like to be more looking for a hook on webapp's startup. In that case, you rather want a ServletContextListener
.
@WebListener
public class Config implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
// Do your thing during webapp's startup.
}
public void contextDestroyed(ServletContextEvent event) {
// Do your thing during webapp's shutdown.
}
}
如果您尚未使用Servlet 3.0(因此无法使用@WebListener
),则需要按如下所示在web.xml
中手动注册它:
If you're not on Servlet 3.0 yet (and thus can't use @WebListener
), then you need to manually register it in web.xml
as follows:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
另请参见:
- Servlet容器生命周期
- Servletcontainer lifecycle
See also:
这篇关于web.xml中的load-on-startup是否可以用于在启动时加载任意类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!