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>
精彩评论