<分区>
我读过 this但我不太明白它是如何工作的。我想在我的 Web 应用程序启动时加载一个属性文件并设置我的连接池。显然我只想在一个地方做一次,所以如果需要我可以改变它。对于常规的 servlet,我只是将我的初始化代码放在 servlet 的 init() 方法中,但您无法使用 Jersey servlet 访问它。那么我该在哪里做呢?上面链接中的监听器是如何工作的?
<分区>
我读过 this但我不太明白它是如何工作的。我想在我的 Web 应用程序启动时加载一个属性文件并设置我的连接池。显然我只想在一个地方做一次,所以如果需要我可以改变它。对于常规的 servlet,我只是将我的初始化代码放在 servlet 的 init() 方法中,但您无法使用 Jersey servlet 访问它。那么我该在哪里做呢?上面链接中的监听器是如何工作的?
最佳答案
您需要做的就是编写一个实现 ServletContextListener 接口(interface)的 java 类。此类必须实现两个方法 contextInitialized 方法,该方法在首次创建 Web 应用程序时调用,而 contextDestroyed 方法在销毁时调用。您要初始化的资源将在 contextInitialized 方法中实例化,并在 contextDestroyed 类中释放资源。应用程序必须配置为在部署时调用此类,这在 web.xml 描述 rune 件中完成。
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 方法所做的类似。
关于java - 在 Jersey webapp 启动时初始化数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12875682/