webapp启动时初始化数据库

webapp启动时初始化数据库

本文介绍了在Jersey webapp启动时初始化数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读但我不太明白它是如何工作的。我想在我的Web应用程序启动时加载属性文件并设置我的连接池。显然我只想在一个地方做一次,所以如果需要我可以改变它。使用常规servlet,我只需将初始化代码放在servlet的init()方法中,但是您无法使用Jersey servlet访问它。那我该怎么办?上面链接中的监听器如何工作?

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?

推荐答案

您需要做的就是编写一个实现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

}

网络.xml配置

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

现在,当应用程序部署并实例化Connection或任何其他应用程序时,应用程序将调用ServletContextClass contextInitialized方法中的资源位置与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.

这篇关于在Jersey webapp启动时初始化数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:30