views:

158

answers:

2

I have a simple web app, with a few jsp pages, servlets and pojo's. I want to initialise the connection pool before any requests are made. What is the best way to do this? Can it be done when the app is first deployed or do you have to wait till the first request comes in?

A: 

What about a basic startup servlet to initialise the connection pool?

Nerdfest
+6  A: 

Use an ServletContextListener and declare it properly in web.xml. This way is preferable to a startup servlet. It is more organized, and your intent is obvious. It is also guaranteed to run before any request. It also gives you a shutdown hook to clear the pool.

Here is a snippet from my web.xml, for example:

<listener>
  <listener-class>
    com...ApplicationListener
  </listener-class>
</listener>

and here is a code snippet from the class itself. Make sure that you catch exceptions so they don't propagate to your server application, and provide helpful log messages - those will help you when you are tracing your application.

public class ApplicationListener implements ServletContextListener {

  private ServletContext sc = null;

  private Logger log = Logger
    .getLogger(ApplicationListener.class);

  public void contextInitialized(ServletContextEvent arg0) {
    this.sc = arg0.getServletContext();
    try {
      // initialization code
    } catch (Exception e) {
      log.error("oops", e);
    }
    log.info("webapp started");
  }

  public void contextDestroyed(ServletContextEvent arg0) {
    try {
      // shutdown code
    } catch (Exception e) {
      log.error("oops", e);
    }
    this.sc = null;
    log.info("webapp stopped");
  }

}

See the api here and examples here.

Yoni
You consider "oops" a helpful message? :-)
extraneon
it is the most universally accepted indication that something is really wrong :)
Yoni