有没有办法从Java Bean访问web.xml属性?

mat*_*t b 4 java servlets

Servlet API中是否有任何方法可以从与Web容器完全无关的Bean或Factory类中访问web.xml中指定的属性(例如初始化参数)?

例如,我正在编写一个Factory类,我想在Factory中包含一些逻辑来检查文件和配置位置的层次结构,以查看哪些可用于确定实例化哪个实现类 - 例如,

  1. 类路径中的属性文件,
  2. 一个web.xml参数,
  3. 系统属性,或
  4. 一些默认逻辑,如果没有别的可用.

我希望能够在不注入任何引用ServletConfig或类似于我的工厂的任何内容的情况下执行此操作- 代码应该能够在Servlet容器之外运行.

这可能听起来有点不常见,但是我想要这个组件,我正在努力与我们的一个webapp一起打包,并且还具有足够的通用性,可以与我们的一些命令行工具一起打包需要一个新的属性文件只为我的组件 - 所以我希望捎带在其他配置文件,如web.xml.

如果我没记错的话,.NET有一些东西Request.GetCurrentRequest()可以获得对当前正在执行的引用Request- 但由于这是一个Java应用程序,我正在寻找可以用来访问的类似的东西ServletConfig.

too*_*kit 5

你可以这样做的一种方法是:

public class FactoryInitialisingServletContextListener implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent event) {
    }

    public void contextInitialized(ServletContextEvent event) {
        Properties properties = new Properties();
        ServletContext servletContext = event.getServletContext();
        Enumeration<?> keys = servletContext.getInitParameterNames();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            String value = servletContext.getInitParameter(key);
            properties.setProperty(key, value);
        }
        Factory.setServletContextProperties(properties);
    }
}

public class Factory {

    static Properties _servletContextProperties = new Properties();

    public static void setServletContextProperties(Properties servletContextProperties) {
        _servletContextProperties = servletContextProperties;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的web.xml中包含以下内容

<listener>
    <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

如果您的应用程序在Web容器中运行,则在创建上下文后,容器将调用该侦听器.在这种情况下,_servletContextProperties将替换为web.xml中指定的任何context-params.

如果您的应用程序在Web容器外部运行,则_servletContextProperties将为空.