访问 war 中的属性文件
Accessing properties file in a war
我正在尝试访问 war 中的属性文件。代码正在运行,但是当我将代码导出到 war 并使用 Fiddler 使用 POST(具有可接受的输入)时,它找不到 config.properties。 (空指针异常)
输入和网络服务 运行 正确。只是想找出一种在使用 war.
时编辑我的属性的方法
一些事实:
我制作了一个 RetreivePropertiesClass。这使用:
properties.load(this.getClass()
.getResourceAsStream("/WEB-INF/config.properties"));
我的属性文件路径:
/com.webapp/WebContent/WEB-INF/config.properties
我正在尝试使用属性数据:
String url = RetreiveProperties.getUrl();
String driver = RetreiveProperties.getDriver();
String username = RetreiveProperties.getUsername();
String password = RetreiveProperties.getPassword();
// line below causes the NullPointerException
Class.forName(driver);
Getter 使用:
public static String getDriver() {
return driver = properties.getProperty("jdbc.driver");
}
部署war时,属性文件在:
webapps\com.webapp1\WEB-INF\config.properties
Config.properties:
jdbc.url = jdbc:postgresql://127.0.0.1:2222/gisdb
jdbc.driver = org.postgresql.Driver
jdbc.username = postgres
jdbc.password = admin
我已经尝试计算给出的示例 here and here。由于未加载属性文件,一直给出 NullPointerException。
任何人都可以把我推向正确的方向吗?
干杯!
如果您要从类路径加载属性文件,它必须位于 war 内的 WEB-INF/classes
目录中。 (或在 WEB-INF/lib
内的罐子内)。 WEB-INF
目录本身不在类路径中。
如果您确保文件以 WEB-INF/classes/config.properties
结束,如果您将 getResourceAsStream
调用更改为 getResourceAsStream("/config.properties")
,您的上述代码应该可以工作
如果方法是静态方法,getClass()方法会失败,提示“Cannot make a static reference to the non-static method getClass() from the type Object”
相反,您应该使用 CurrentClass.class.getClassLoader().getResourceAsStream.
来源:here
我正在尝试访问 war 中的属性文件。代码正在运行,但是当我将代码导出到 war 并使用 Fiddler 使用 POST(具有可接受的输入)时,它找不到 config.properties。 (空指针异常)
输入和网络服务 运行 正确。只是想找出一种在使用 war.
时编辑我的属性的方法一些事实:
我制作了一个 RetreivePropertiesClass。这使用:
properties.load(this.getClass() .getResourceAsStream("/WEB-INF/config.properties"));
我的属性文件路径:
/com.webapp/WebContent/WEB-INF/config.properties
我正在尝试使用属性数据:
String url = RetreiveProperties.getUrl(); String driver = RetreiveProperties.getDriver(); String username = RetreiveProperties.getUsername(); String password = RetreiveProperties.getPassword(); // line below causes the NullPointerException Class.forName(driver);
Getter 使用:
public static String getDriver() { return driver = properties.getProperty("jdbc.driver"); }
部署war时,属性文件在:
webapps\com.webapp1\WEB-INF\config.properties
Config.properties:
jdbc.url = jdbc:postgresql://127.0.0.1:2222/gisdb jdbc.driver = org.postgresql.Driver jdbc.username = postgres jdbc.password = admin
我已经尝试计算给出的示例 here and here。由于未加载属性文件,一直给出 NullPointerException。
任何人都可以把我推向正确的方向吗?
干杯!
如果您要从类路径加载属性文件,它必须位于 war 内的 WEB-INF/classes
目录中。 (或在 WEB-INF/lib
内的罐子内)。 WEB-INF
目录本身不在类路径中。
如果您确保文件以 WEB-INF/classes/config.properties
结束,如果您将 getResourceAsStream
调用更改为 getResourceAsStream("/config.properties")
如果方法是静态方法,getClass()方法会失败,提示“Cannot make a static reference to the non-static method getClass() from the type Object”
相反,您应该使用 CurrentClass.class.getClassLoader().getResourceAsStream.
来源:here