3

I'm trying to get a J2EE server to register (read: send some message to) with another server on its own initiative - not as a response to something. Surprisingly, I've found very little information or questions on whether there are events and/or classes to extend that will give me a handle on "server-start". I could always write a script that first deploys to server, then prompts it with a request, but I'd really rather have a cleaner solution..

Thanks.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
vivri
  • 885
  • 2
  • 12
  • 23

1 Answers1

6

Implement ServletContextListener and do the job in contextInitialized() method.

public class Config implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during server startup.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during server shutdown.
    }

}

When you're using Tomcat 7, register it as follows to get it to run

@WebListener
public class Config implements ServletContextListener {

Or when using Tomcat 6 or older, register it in web.xml instead

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I wonder why the ServletContext mem-store is unavailable there. This doesn't seem very logical, and it's too bad, because I can't initialize attributes that will be available later on, too. – vivri May 10 '11 at 16:22
  • 1
    It's available by `event.getServletContext()`. See also [those answers](http://stackoverflow.com/search?tab=votes&q=user%3a157882%20%22public%20class%20config%20implements%20servletcontextlistener%22), particularly [this one](http://stackoverflow.com/questions/3468150/using-init-servlet/3468317#3468317). – BalusC May 10 '11 at 16:22
  • Again, thanks a lot. I wasn't aware of that area in the API. – vivri May 10 '11 at 17:48