views:

47

answers:

1

I want to be able to load my configuration for the webapp at startup of tomcat (apache commons configuration library) is this a possible way:

public class MyAppCfg implements javax.servlet.ServletContextListener {

private ServletContext context = null;

@Override
public void contextInitialized(ServletContextEvent event) {
    try{
        this.context = event.getServletContext();

        XMLConfiguration config = new XMLConfiguration("cfg.xml");
        config.setReloadingStrategy(new FileChangedReloadingStrategy());

        this.context.setAttribute("mycfg", config);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    this.context = null;
   }
}

web.xml

<listener>
    <listener-class>mypackage.MyAppCfg</listener-class>    
</listener>

and later acces them in the webapp via

this.cfg = (XMLConfiguration) servletRequest.getAttribute("mycfg");
+1  A: 

No. You wouldn't be able to get the configuration this way. You are setting it in servlet context but retrieving it in request context.

You need to retrieve the cfg in your Servlet init like this,

public void init(final ServletConfig config) {
        // log it to the ServletContext
        ServletContext context = config.getServletContext();
        this.cfg = (Configuration)context.getAttribute("mycfg");
}
ZZ Coder