简体   繁体   中英

properties file call in Java servlet

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?

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"));

Read more...


Alternately

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM