我从 Java 中的属性文件开始,我正在关注 this tuto
它在我的应用程序中工作得很好,除非我想要 servlet 中的属性。 如果从 servlet 或“普通”类执行相同的函数调用,则不会给出相同的结果。 路径出错了,我不知道为什么。 也许来自 servlet 的路径来自服务器。
input = new FileInputStream(filename);
prop.load(input);
当我使用 servlet 执行这些行时,filename
的路径在哪里?
最佳答案
where is the path for
filename
when I execute these lines with the servlet?
这可能对您有帮助:
File file = new File(filename);
System.out.println(file.getAbsolutePath());
<小时/>
如果属性文件确实存在于您想要保存的位置,那么您应该通过 ServletContext#getResourceAsStream()
将其作为 Web 内容资源获取.
示例代码:
properties.load(getServletContext()
.getResourceAsStream("/WEB-INF/properties/sample.properties"));
<小时/>
或者
注册 ServletContextListener在服务器启动时加载 Init 参数,您可以随时更改配置文件位置,而无需更改任何 java 文件。
加载属性并使其对其他类静态可见。
示例代码:
public class AppServletContextListener implements ServletContextListener {
private static Properties properties;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
String cfgfile = servletContextEvent.getServletContext().getInitParameter("config_file");
properties.load(new FileInputStream(cfgfile));
}
public static Properties getProperties(){
return properties;
}
}
web.xml:
<listener>
<listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>
<context-param>
<param-name>config_file</param-name>
<param-value>config_file_location</param-value>
</context-param>
关于java - Java servlet 中的属性文件调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24868826/