Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load properties file in Servlet/JSP [duplicate]

I've created a jar from my Java project and wanted to use the same jar in a JSP Servlet Project. I'm trying to load a property file let say sample.properties from my JSP Servlet Project kept in WEB/properties/sample.properties which should be read by a class in the jar.I'm using the following code wriiten in a class of jar to access it.

Properties prop=new Properties();
prop.load(/WEB-INF/properties/sample.properties);

But each time I'm getting fileNotFound exception.
Please suggest me the solution.

Here is the structure

WEB-INF
      |
       lib
          |
           myproject.jar
                       |
                        myclass (This class needs to read sample.properties)
      |
       properties
                 |sample.properties
like image 487
bitsbuffer Avatar asked Sep 20 '12 06:09

bitsbuffer


1 Answers

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?
like image 77
BalusC Avatar answered Nov 15 '22 08:11

BalusC