我想使用一个在部署到Server后只调用一次的方法

meb*_*ada 7 java servlets initialization

我是Servlets的新手.我想使用一个在部署到服务器后只调用一次的方法.我看了看HttpServlet#init().但我发现每个请求都会调用它.我误解了吗?有什么替代方案init()

Bal*_*usC 21

不,在每个请求中都没有调用它.它仅在servlet初始化期间调用,通常在webapp的生命周期中只发生一次.另请参阅此答案,了解有关如何创建和执行servlet的更多详细信息.

如果你真的想做一些全局/应用程序范围的初始化(因此本身并不仅仅与特定的servlet绑定),那么你通常会使用ServletContextListenerfor.您可以在contextInitialized()方法中执行初始化操作.

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class Config implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }
    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你Servlet 3.0还没有升级,因此无法使用@WebListener注释,那么你需要手动注册它,/WEB-INF/web.xml如下所示:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)