Initialize database on Jersey webapp startup

All you need to do is write a java class that implements the ServletContextListener interface. This class must implement two method contextInitialized method which is called when the web application is first created and contextDestroyed which will get called when it is destroyed. The resource that you want to be initialized would be instantiated in the contextInitialized method and the resource freed up in the contextDestroyed class. The application must be configured to call this class when it is deployed which is done in the web.xml descriptor file.

public class ServletContextClass implements ServletContextListener
{
    public static Connection con;

    public void contextInitialized(ServletContextEvent arg0) 
    {
        con.getInstance ();     
    }//end contextInitialized method

    public void contextDestroyed(ServletContextEvent arg0) 
    {
        con.close ();       
    }//end constextDestroyed method
}

The web.xml configuration

<listener>
    <listener-class>com.nameofpackage.ServletContextClass</listener-class>
</listener>

This now will let the application call the ServletContextClass when the application is deployed and instantiate the Connection or any other resource place in the contextInitialized method some what similar to what the Servlet init method does.


Since you don't need to modify Jersey itself at startup time you probably don't want an AbstractResourceModelListener. What you want is a javax.servlet.ServletContextListener. You can add listener elements to your web.xml in the same way you add servlet elements. The ServletContextListener will get called when your context (web application) first gets created and before the Jersey servlet is started. You can do whatever you need to the database in this listener and it will be ready when you start using Jersey.