【问题标题】:Accessing properties file in a war在战争中访问属性文件
【发布时间】:2015-06-28 18:12:13
【问题描述】:

我正在尝试在战争中访问我的属性文件。代码正在运行,但是当我将代码导出到战争中并使用 Fiddler 使用 POST(带有接受的输入)时,它找不到 config.properties。 (NullPointerException)

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

一些事实:

  • 我已经创建了一个 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);
    
  • 使用吸气剂:

    public static String getDriver() {
    return driver = properties.getProperty("jdbc.driver");
    }
    
  • war部署时,properties文件在:

    webapps\com.webapp1\WEB-INF\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。

谁能把我推向正确的方向?

干杯!

【问题讨论】:

  • 查看打包后的war文件,属性文件的路径是什么?
  • 啊,忘记说了。它在 C:\Users\myusername\Downloads\apache-tomcat-8.0.21-windows-x64\apache-tomcat-8.0.21\webapps\com.webapp1\WEB-INF

标签: java web-applications properties war


【解决方案1】:

如果你要从类路径加载属性文件,它必须在你的战争中的WEB-INF/classes 目录中。 (或在 WEB-INF/lib 内的罐子内)。 WEB-INF 目录本身不在类路径中。

如果您确保文件以WEB-INF/classes/config.properties 结尾,那么如果您将getResourceAsStream 调用更改为getResourceAsStream("/config.properties"),上述代码应该可以工作

【讨论】:

  • 我把我的属性文件放在:C:\Users\myusername\Downloads\apache-tomcat-8.0.21-windows-x64\apache-tomcat-8.0.21\webapps\com.webapp1\ WEB-INF\classes\com\webapp。我正在使用 properties.load(this.getClass().getResourceAsStream("WEB-INF/classes/com/webapp/config.properties"));获取文件,但它仍然无法正常工作。我打错字了吗?
  • P.S. C:\ 地址是我查看 war 文件时存储属性文件的目录。
  • @Camelaria 如果将其放在该路径中,则需要调用 getResourceAsStream("/com/webapp/config.properties")
  • 嗯,将加载器更改为 /com/webapp/config.properties。仍然在 Class.forName(driver); 处获得 NullPointerException。这是我第一次使用属性值的地方。
  • @Camelaria 请发布堆栈跟踪。它实际上是你得到的流为 null 还是其他什么?
【解决方案2】:

如果方法是静态方法,getClass()方法会失败,提示“Cannot make a static reference to the non-static method getClass() from type Object”。

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

来源:here

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 2014-06-04
    • 2011-12-18
    • 1970-01-01
    • 2011-03-22
    • 2013-03-25
    • 2023-04-04
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多