【问题标题】:Why is contextInitialized() called multiple times?为什么多次调用 contextInitialized()?
【发布时间】:2010-08-22 20:23:26
【问题描述】:

我在 Jboss 4.2.3.GA 上运行一个 Stripes Web 应用程序,并在我启动 JBoss 时尝试调用一个方法。我像这样创建了一个 ServletContextListener:

public class TimerContextListener implements ServletContextListener {

    @Inject
    private TimerManager timerManager;

    public void contextInitialized(ServletContextEvent servletcontextevent) {
        ((Injector) servletcontextevent.getServletContext().getAttribute(GuiceServletContextListener.KEY)).injectMembers(this);
        timerManager.stopAllTimers();
        timerManager.startTimer();
    }

    public void contextDestroyed(ServletContextEvent servletcontextevent) {

    }
}

我在 web.xml 中添加了一个条目,如下所示:

<listener>
        <listener-class>com.lawless.web.servletContextListeners.TimerContextListener</listener-class>
    </listener>

但是当我启动我的服务器时,contextInitialized() 被调用了 3 次。知道问题可能是什么吗?谢谢。

【问题讨论】:

  • 在您的contextInitialized 顶部放置一个基本的System.out.println,以确保您看到的是您认为您所看到的。顺便说一句,我已经看到了这种问题:将 Tomcat 连接到 NetBeans 以用于开发时的一个已知错误导致Tomcat double-launching the web app

标签: java servlets jboss stripes


【解决方案1】:

好的,我想通了。它被调用了 3 次,因为我在 jboss-web.xml 中定义了 3 个虚拟主机。不知道为什么它会导致这种行为。如果有人能解释原因,我将不胜感激。

【讨论】:

    【解决方案2】:

    每个网络应用程序只有一个ServletContextServletContext 将在部署应用程序时创建(3 个虚拟主机意味着部署到具有 3 个不同 IP 地址的 3 个不同主机)。一旦创建了ServletContext,它将被同一应用程序中的所有servlet 和JSP 文件使用。 ServletContext在Web应用场景中也称为应用范围变量。

    来源 - http://www.javabeat.net/2009/02/servletcontextlistener-example/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-16
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      相关资源
      最近更新 更多