views:

90

answers:

1

Hello,

I have an XML file which I need to read and load the data in memory every time the app launches. So, while the project was in Eclipse, i hardcoded the path: "/path/to/xml" but when I create the WAR, how can I specify the relative path to the XML file.

I can do it using URL url = getServletContext().getResource(fileName);

But, I don't have the servlet context available to me, since it's just a Config loader class.

Thanks

UPDATE:

I did this, was the simplest approach:

URL urlOfXml =

Thread.currentThread().getContextClassLoader().getResource("ConfigXmlFile.xml");
A: 

Implement ServletContextListener. In the contextInitialized() method which get called during webapp's startup you've got a handle to ServletContextEvent which in turns offers you the getServletContext() method.

public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        URL url = event.getServletContext().getResource(fileName);
        // ...
    }

    // ...
}

Register it in web.xml as a <listener>.

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
BalusC
so, contextInitialized(ServletContextEvent event) method will be invoked automatically when the web app starts?
zengr
If registered in web.xml, yes. Note the blue text in my answer. Those are links. Click and read them.
BalusC