且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Jersey webapp 启动时初始化数据库

更新时间:2021-09-10 03:31:55

您需要做的就是编写一个实现 ServletContextListener 接口的 java 类.此类必须实现两个方法 contextInitialized 方法,该方法在首次创建 Web 应用程序时调用,而 contextDestroyed 方法将在销毁时调用.您要初始化的资源将在 contextInitialized 方法中实例化,并在 contextDestroyed 类中释放资源.应用程序必须配置为在部署时调用此类,这在 web.xml 描述符文件中完成.

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
}

web.xml 配置

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

这将让应用程序在部署应用程序时调用 ServletContextClass 并在 contextInitialized 方法中实例化 Connection 或任何其他资源位置,这与 Servlet init 方法所做的有些类似.

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.