在 Jersey webapp 启动时初始化数据库 [英] Initialize database on Jersey webapp startup

查看:28
本文介绍了在 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
}

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆