我希望能够在启动tomcat(apache commons配置库)时为webapp加载我的配置,这是一种可行的方法:
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>
然后通过
在webapp中访问它们this.cfg = (XMLConfiguration) servletRequest.getAttribute("mycfg");
答案 0 :(得分:1)
没有。您将无法以这种方式获得配置。您在servlet上下文中设置它,但在请求上下文中检索它。
您需要像这样在Servlet init中检索cfg,
public void init(final ServletConfig config) {
// log it to the ServletContext
ServletContext context = config.getServletContext();
this.cfg = (Configuration)context.getAttribute("mycfg");
}