[英]Read Properties file in WEB-INF folder java using init
我正在尝试读取WEB-INF中的属性文件,但我得到的只是null。 我是Java Web开发的新手。
我的初始化方法:
@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;
}
我的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>
我知道我一定会丢失一些东西,因为字符串getDataBaseUrl返回null。 请帮忙。
看一下这个:
<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());
}
}
我要么
1)将属性放入WEB-INF/classes
并使用getClass().getResourceAsStream()
进行加载。
要么
2)将完整的文件路径放入web.xml(并将文件放在Web应用程序之外的位置到用户可编辑的配置区域中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.