Search code examples
javaweb-applicationspropertieswar

Accessing properties file in a war


I'm trying to access my properties file in a war. The code is working, but when i'm exporting the code into a war and use a POST (with an accepted input) using Fiddler, it cannot find the config.properties. (NullPointerException)

The input and webservice are running correctly. Just trying to figure out a way to edit my properties while using a war.

Some facts:

  • I've made a RetreivePropertiesClass. This uses:

    properties.load(this.getClass()
                        .getResourceAsStream("/WEB-INF/config.properties"));
    
  • My properties file path:

    /com.webapp/WebContent/WEB-INF/config.properties
    
  • I'm trying to use the properties data in:

    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 used:

    public static String getDriver() {
    return driver = properties.getProperty("jdbc.driver");
    }
    
  • When the war is deployed, the properties file is in:

    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
    

I already tried to work out the examples given here and here. Keeps giving the NullPointerException because the properties file isn't loaded.

Can anyone push me in the right direction?

Cheers!

NullPointer in TomCat8


Solution

  • If the method is a static method, the getClass() method will be failed, and prompts “Cannot make a static reference to the non-static method getClass() from the type Object“.

    Instead, you should use CurrentClass.class.getClassLoader().getResourceAsStream.

    Source: here