zengr
zengr

Reputation: 38899

Get relative path to XML file from a non-servlet class in a WAR

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

Upvotes: 2

Views: 2386

Answers (1)

BalusC
BalusC

Reputation: 1108922

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>

Upvotes: 2

Related Questions