14

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

4

2 回答 2

40

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

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 方法所做的类似。

于 2012-10-13T18:48:01.357 回答
3

由于您不需要在启动时修改 Jersey 本身,因此您可能不需要 AbstractResourceModelListener。你想要的是一个javax.servlet.ServletContextListener。您可以像添加 servlet 元素一样将侦听器元素添加到 web.xml。ServletContextListener 将在您的上下文(Web 应用程序)首次创建时和 Jersey servlet 启动之前被调用。您可以在此侦听器中对数据库执行任何您需要的操作,当您开始使用 Jersey 时,它就会准备就绪。

于 2012-10-13T18:30:25.787 回答