使用init在WEB-INF文件夹java中读取Properties文件

Err*_*ion 1 java servlets properties

我正在尝试读取WEB-INF中的属性文件,但我得到的只是null.我是java web开发的新手.

我的init方法:

 @Override
    public void init() throws ServletException {
        try {
            String path = "";
            path = "/WEB-INF/" + getServletContext().getInitParameter("monpesapropertiesfile");
            String realPath;
            realPath = getServletContext().getRealPath(path);
            if(realPath != null){
                 InputStream fis = new FileInputStream(realPath);
                 prop.load(fis);
            }
        } catch (Exception asd) {
            System.out.println(asd.getMessage());
        }
    }
    public String getDatabaseUrl() {
        String url = prop.getProperty("database.url");
        return url;
    }
Run Code Online (Sandbox Code Playgroud)

我的Web.xml:

<context-param>
        <param-name>monpesapropertiesfile</param-name>
        <param-value>monpesaproperties.properties</param-value>
    </context-param>
    <servlet>
        <servlet-name>ReadProperty</servlet-name>
        <servlet-class>com.monpesa.properties.ReadProperty</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
Run Code Online (Sandbox Code Playgroud)

我知道我必须遗漏一些东西,因为String getDataBaseUrl返回null.请帮忙.

acc*_*c15 6

看一下这个:

http://docs.oracle.com/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/javax/servlet/ServletContext.html#getResource(java.lang.String)

<context-param>
    <param-name>monpesapropertiesfile</param-name>
    <param-value>/WEB-INF/monpesaproperties.properties</param-value>
</context-param>

public void init() throws ServletException {
    try {
        String path = getServletContext().getInitParameter("monpesapropertiesfile");
        final InputStream is = getServletContext().getResourceAsStream(path);
        try {
            prop.load(is);
        } finally {
            is.close();
        }
    } catch (Exception asd) {
        System.out.println(asd.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)