1

我实际上有一个带有 servlet 的程序:

@WebServlet("/Controler")
public class Controler extends HttpServlet {

}

我需要file.properties在我的程序中使用属性文件:要加载它,我有一个类:

public class PropLoader {

    private final static String m_propertyFileName = "file.properties";

    public static String getProperty(String a_key){

        String l_value = "";

        Properties l_properties = new Properties();
        FileInputStream l_input;
        try {

            l_input = new FileInputStream(m_propertyFileName); // File not found exception
            l_properties.load(l_input);

            l_value = l_properties.getProperty(a_key);

            l_input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return l_value;

    }

}

我的属性文件位于 WebContent 文件夹中,我可以通过以下方式访问它:

String path = getServletContext().getRealPath("/file.properties");

但是我不能在servlet之外的另一个类中调用这些方法......

如何在 PropLoader 类中访问我的属性文件?

4

2 回答 2

2

如果你想从 webapp 结构中读取文件,那么你应该使用ServletContext.getResourceAsStream(). 当然,由于你是从 webapp 加载它,你需要一个对代表 webapp 的对象的引用:ServletContext。init()您可以通过在您的 servlet 中重写、调用getServletConfig().getServletContext()并将 servlet 上下文传递给加载文件的方法来获得这样的引用:

@WebServlet("/Controler")
public class Controler extends HttpServlet {
    private Properties properties;

    @Override
    public void init() {
        properties = PropLoader.load(getServletConfig().getServletContext());
    }
}

public class PropLoader {

    private final static String FILE_PATH = "/file.properties";

    public static Properties load(ServletContext context) {
        Properties properties = new Properties();
        properties.load(context.getResourceAsStream(FILE_PATH));
        return properties;
    }
}    

请注意,必须处理一些异常。

另一种解决方案是将文件放在WEB-INF/classes已部署的 webapp 中,并使用 ClassLoader 加载文件:getClass().getResourceAsStream("/file.properties"). 这样,您就不需要引用ServletContext.

于 2013-07-17T13:53:22.420 回答
1

我建议使用 getResourceAsStream 方法(下面的示例)。它需要属性文件位于 WAR 类路径中。

InputStream in = YourServlet.class.getClassLoader().getResourceAsStream(path_and_name);

问候栾

于 2013-07-17T13:49:56.187 回答