如何在 servlet 准备好提供服务后在 tomcat 中获得通知? (ServletContextListener 较早)

How to get a notification in tomcat AFTER a servlet is ready to serve? (ServletContextListener is early)

我想在 tomcat 加载 servlet 并准备好服务时在启动时收到通知。我想在此通知中对此 servlet 进行 http 调用。

我已经尝试将 ServletContextListener 添加到我的 web.xml,但是当我收到 contextInitialized 回调时,servlet 似乎没有完全加载,当我尝试时收到 404对其进行 http 调用。

编辑:

如果我在 myServletContextListener 中进行 http 调用之前(在另一个线程上以免阻塞)休眠大约 20 秒。 contextInitialized() impl,它工作正常。所以我很确定我在 servlet 准备好调用之前就收到了事件。

public class StartupListener implements javax.servlet.ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {

    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            Thread.sleep(20000L);
            Target target = ClientBuilder.newClient().target("http://localhost:8080/myapp");
            target.path(endpoint).request().get(String.class);
        }
    });
}

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {

}

}

第一次向服务器发出映射请求时加载 servlet,404 表示部署或请求有问题URL

没有可靠的方法可以确定 servlet 是否已准备好处理请求。 来自 servlet (3.0) 规范的 §2.3.1:

The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request.

ServletContextListener.contextInitialized(...) 方法在您的 Web 应用程序启动时调用,与单个 servlet 的生命周期无关。

您可能 post 在 servlet 的 init 方法结束时发出某种通知,认识到您的 servlet 仅接近 就绪。

或者,您可以通过编写 org.apache.catalina.core.StandardContextorg.apache.catalina.core.StandardWrapper 的扩展来实现您想要的,但这超出了正常应用程序开发的范围。