简体   繁体   中英

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!

TomCat8 中的空指针

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM