【问题标题】:Load a properties file in a servlet在 servlet 中加载属性文件
【发布时间】:2014-04-30 22:23:13
【问题描述】:

我在 WEB-INF 中有一个属性文件,其中包含一些我的 servlet 需要使用的属性(属性,如数据库密码……)。加载此文件的最佳方法是什么?我应该重写 servlet 的 init 方法,以便只加载一次文件吗?

谢谢

【问题讨论】:

  • 我正在使用 Netbeans 和 JBoss AS7
  • 这些参数是否仅适用于一个 servlet,或者它们是否也适用于其他 servlet?
  • 它们也将被其他 servlet 使用
  • 为什么这些不是 web.xml 中的上下文参数?听起来这是一个很好的用例......
  • 由于会有很多参数,我更喜欢将它们放在单独的文件中。

标签: java jakarta-ee servlets


【解决方案1】:

我并不是说这种方式是正确的,因为我不使用 JEE,但据我所知,您可以为此使用 ServletContextListener 方法。像这样实现它

class ContextListenerImpl implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //lets skip it for now
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ServletContext sc = sce.getServletContext();

        //read parameter from properties and add it to servlet context attributes
        sc.setAttribute("yourParameterName", "value");
    }

}

您应该可以通过例如在任何 servlet 中使用它

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    //...
    getServletContext().getAttribute("yourParameterName");
    //...
}

BTW 属性值也可以包含其他对象,而不仅仅是字符串。

哦,别忘了将此侦听器添加到您的 Web 应用程序中。只需添加

<listener>
    <listener-class>full.name.of.ContextListenerImpl</listener-class>
</listener>

到您的web.xml 文件。

【讨论】:

  • 此解决方案是否允许其他 servlet 访问相同的属性?
  • 是的,整个 Web 应用程序应该只有一个 ServletContext,因此 getServletContext() 应该在所有 servlet 中返回此类的相同实例。这也是我们通过sce.getServletContext(); 在侦听器中获得的相同实例,因此所有 servlet 都将从相同的ServletContext 读取属性。
猜你喜欢
  • 2013-09-01
  • 2012-09-12
  • 2011-02-18
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
相关资源
最近更新 更多