在战争中访问属性文件

时间:2015-06-28 18:12:14

标签: java web-applications properties war

我试图在战争中访问我的属性文件。代码正在运行,但是当我将代码导入战争并使用Fiddler使用POST(使用已接受的输入)时,它无法找到config.properties。 (空指针异常)

输入和网络服务正常运行。试图找出一种在使用战争时编辑我的属性的方法。

一些事实:

  • 我制作了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");
    }
    
  • 部署战争时,属性文件位于:

    web应用\ 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

我已经尝试制定了herehere给出的示例。继续给出NullPointerException,因为没有加载属性文件。 任何人都可以把我推向正确的方向吗?

干杯!

NullPointer in TomCat8

2 个答案:

答案 0 :(得分:1)

If you are going to load the properties file from the classpath, it must be in the WEB-INF/classes directory inside of your war. (Or inside a jar inside of WEB-INF/lib ). The WEB-INF directory itself is not on the classpath.

If you make sure the file ends up as WEB-INF/classes/config.properties your above code should work if you change the getResourceAsStream call to getResourceAsStream("/config.properties")

答案 1 :(得分:1)

如果方法是静态方法,则getClass()方法将失败,并提示“无法从类型Object中对非静态方法getClass()进行静态引用”。

相反,你应该使用 CurrentClass.class.getClassLoader()。getResourceAsStream。

来源:here

相关问题