Reputation: 1661
I was testing out reading a properties file using getResourceAsStream when the properties file is in classpath (under WEB-INF\lib folder). And it is not working for some reason. Can anybody tell me what I am doing wrong?
This is my environment: Operating system is Windows 7. IDE is Eclipse 4.2.3 Kepler 64-bit. Server is Tomcat 6.0.37 running on 8081 port.
I created a web application MyWebProject.
I have a app.properties
file which is located in WEB-INF\lib
folder. This is the content of app.properties
file:
DataSource=jdbc/MyDB
I created a class AppProperties
which reads this file. This is the class:
public final class AppProperties {
private static String DATA_SOURCE_NAME;
public static String getDataSourceName() {
return DATA_SOURCE_NAME;
}
static {
ClassLoader classLoader = null;
InputStream propertiesFile = null;
Properties properties = null;
final String PROPERTIES_FILE_NAME = "app.properties";
properties = new Properties();
classLoader = Thread.currentThread().getContextClassLoader();
System.out.println("AppProperties: Name of classLoader = " + classLoader.getClass().getName());
propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE_NAME);
System.out.println("AppProperties: propertiesFile = " + propertiesFile);
}
}
Then I created a Servlet AppPropertiesServlet
to test it out:
public class AppPropertiesServlet extends HttpServlet {
public AppPropertiesServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String dataSourceName = null;
dataSourceName = AppProperties.getDataSourceName();
}
}
I deployed the web application MyWebProject on Tomcat. So under webapps
folder of Tomcat, a new folder MyWebProject
was created with all the necessary files. I then run the servlet http://localhost:8081/MyWebProject/AppPropertiesServlet
and this is what appears on Tomcat console:
AppProperties: Name of classLoader = org.apache.catalina.loader.WebappClassLoader
AppProperties: propertiesFile = null
Why the propertiesFile is null? The app.properties
file is in the WEB-INF\lib
folder of MyWebProject
folder but somehow the classloader is unable to find it. Strange. What I am doing wrong here?
Thanks
Upvotes: 0
Views: 747
Reputation: 15446
If you want it to be under WEB-INF/lib
it has to be packaged inside the JAR.
If you want it to be like a normal file , it has to be inside WEB-INF/classes
.
Upvotes: 1