Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize database on Jersey webapp startup [duplicate]

I've read this but I don't quite understand how it works. I want to load a properties file and set up my connection pool when my web application starts. Obviously I want to do this only once and in a single place so I can change it if needs be. With regular servlets, I would simply put my initialization code in the servlet's init() method, but you don't have access to it with a Jersey servlet. So where do I do it? How do the listeners in the link above work?

like image 454
Sotirios Delimanolis Avatar asked Oct 13 '12 18:10

Sotirios Delimanolis


2 Answers

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.

like image 146
Mario Dennis Avatar answered Nov 02 '22 00:11

Mario Dennis


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.

like image 3
Pace Avatar answered Nov 02 '22 01:11

Pace