PSP
PSP

Reputation: 31

How to load a properties file put in the classpath from a JSP?

I have a properties file which I have put in the classpath and I am trying to load it from a JSP:

InputStream stream = application.getResourceAsStream("/alert.properties"); 
Properties props = new Properties(); 
props.load(stream); 

But I am getting a FileNotFoundException.

Upvotes: 3

Views: 3032

Answers (1)

BalusC
BalusC

Reputation: 1108567

The ServletContext#getResourceAsStream() returns resources from the webcontent, not from the classpath. You need ClassLoader#getResourceAsStream() instead.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
properties.load(classLoader.getResourceAsStream("filename.properties"));
// ...

That said, it is considered bad practice to write raw Java code like that in a JSP file. You should be doing that (in)directly inside a HttpServlet or maybe a ServletContextListener class.

Upvotes: 2

Related Questions