开发者

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

开发者 https://www.devze.com 2023-01-10 18:45 出处:网络
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,

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 c开发者_如何学Pythonan 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");


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消