gpt4 book ai didi

java - 使用init读取WEB-INF文件夹java中的属性文件

转载 作者:行者123 更新时间:2023-11-29 10:15:34 24 4
gpt4 key购买 nike

我正在尝试读取 WEB-INF 中的属性文件,但我得到的只是空值。我对 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。请帮忙。

最佳答案

检查一下:

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());
}
}

关于java - 使用init读取WEB-INF文件夹java中的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18894129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com