10

I'm running a Stripes web app on Jboss 4.2.3.GA and am trying to call a method when I start JBoss. I created a ServletContextListener like so:

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) {

    }
}

and I added an entry in web.xml like so:

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

but contextInitialized() is getting called 3 times when I start my server. Any idea what the issue could be? Thanks.

skaffman
  • 398,947
  • 96
  • 818
  • 769
TomahawkPhant
  • 1,130
  • 4
  • 15
  • 33
  • 1
    Put a basic `System.out.println` at the top of your `contextInitialized` to be sure you are seeing what you think you are seeing. By the way I have seen this kind of problem: A known bug when hooking up Tomcat to NetBeans for use in development results in [Tomcat double-launching the web app](https://stackoverflow.com/q/16702011/642706). – Basil Bourque Jun 01 '17 at 22:11

2 Answers2

9

Ok I figured it out. It was being called 3 times because I had 3 virtual hosts defined in my jboss-web.xml. Not sure why it causes that behavior though. If anyone can explain the reason I would appreciate it.

TomahawkPhant
  • 1,130
  • 4
  • 15
  • 33
8

There will be only one ServletContext for each web application. ServletContext will be created while deploying the application (3 Virtual Hosts means deploying to 3 different hosts with 3 different IP addresses). Once the ServletContext is created, it will be used by all the servlets and JSP files in the same application. ServletContext is also called as the application scope variables in the web application scenario.

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

Kkkev
  • 4,716
  • 5
  • 27
  • 43
Ajay
  • 349
  • 1
  • 3
  • 11