Reputation: 514
I am begining with properties files in Java and I am following this tuto
It works very well in my application except when I want a properties in a servlet. The same function call does not give the same result if it is done from the servlet or from a "normal" class. The path becomes wrong and I don't know why. Maybe the path from the servlet is from the server.
input = new FileInputStream(filename);
prop.load(input);
where is the path for filename
when I execute these lines with the servlet?
Upvotes: 0
Views: 884
Reputation: 46881
where is the path for
filename
when I execute these lines with the servlet?
This might help you:
File file = new File(filename);
System.out.println(file.getAbsolutePath());
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()
.
Sample code:
properties.load(getServletContext()
.getResourceAsStream("/WEB-INF/properties/sample.properties"));
Register ServletContextListener to load Init parameters at server start-up where you can change the config file location at any time without changing any java file.
Load properties and make it visible to other classes statically.
Sample code:
public class AppServletContextListener implements ServletContextListener {
private static Properties properties;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
String cfgfile = servletContextEvent.getServletContext().getInitParameter("config_file");
properties.load(new FileInputStream(cfgfile));
}
public static Properties getProperties(){
return properties;
}
}
web.xml:
<listener>
<listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>
<context-param>
<param-name>config_file</param-name>
<param-value>config_file_location</param-value>
</context-param>
Upvotes: 1