Load properties file in Servlet/JSP [duplicate]

Solution 1:

The /WEB-INF folder is not part of the classpath. So any answer here which is thoughtless suggesting ClassLoader#getResourceAsStream() will never work. It would only work if the properties file is placed in /WEB-INF/classes which is indeed part of the classpath (in an IDE like Eclipse, just placing it in Java source folder root ought to be sufficient).

Provided that the properties file is really there where you'd like to keep it, then you should be getting it as web content resource by ServletContext#getResourceAsStream() instead.

Assuming that you're inside a HttpServlet, this should do:

properties.load(getServletContext().getResourceAsStream("/WEB-INF/properties/sample.properties"));

(the getServletContext() is inherited from the servlet superclass, you don't need to implement it yourself; so the code is as-is)

But if the class is by itself not a HttpServlet at all, then you'd really need to move the properties file into the classpath.

See also:

  • Where to place and how to read configuration resource files in servlet based application?

Solution 2:

Try to put sample.properties under src folder, and then

Properties prop = new Properties();
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("myprop.properties"));

Solution 3:

Move your properties files under WEB-INF/classes. Then load it as following:

prop.load(getClass().getResourceAsStream("sample.properties"));

You can put it into sub-directory under classes as well. In this case change the call to getResourceAsStream() accordingly.

To be safer in multi-classloader system you can use Thread.getContextClassLoader().getResourceAsStream() instead.

To make the properties file to arrive to classes folder of your war file you have to put it under resources folder in your project (if you are using maven) or just under src folder if you do not use maven-like directory structure.