在servlet中加载属性文件

时间:2014-04-30 22:23:13

标签: java java-ee servlets

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

由于

1 个答案:

答案 0 :(得分: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文件。

相关问题