Search code examples
javaapache-commons

where to put apache common configuration file


i use apache common configuration library to extract my configuration list when my web started.

but its always thrown error Cannot locate configuration source.

where should i put my configuration file ?

here is web.xml :

<servlet>
    <servlet-name>Quartz</servlet-name>
    <servlet-class>me.myclass.Init</servlet-class>
    <load-on-startup>1</load-on-startup>        
</servlet>

and at my code :

public void init()
{
    XMLConfiguration xmlConfig;
    try {
        xmlConfig = new XMLConfiguration("/WEB-INF/scheduler.xml");
        System.out.println(xmlConfig.getString("master"));
    } catch (org.apache.commons.configuration.ConfigurationException ex) {
        System.out.println(ex);
    } 
}

Solution

  • Since you are in a servlet, I recommend using the servlet context. So long as your file is in WEB-INF it should be located with this code:

      ServletContext context = getServletContext();
      File schedulerFile = new File(context.getResource("/WEB-INF/scheduler.xml").getPath());
      xmlConfig = new XMLConfiguration(schedulerFile);
    

    From the JavaDocs: getResource: Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.