代码之家  ›  专栏  ›  技术社区  ›  matt b

有没有办法从JavaBean访问Web.xml属性?

  •  4
  • matt b  · 技术社区  · 17 年前

    servlet API中是否有任何方法可以从根本不与Web容器关联的bean或工厂类中访问web.xml中指定的属性(例如初始化参数)?

    例如,我正在编写一个工厂类,我想在工厂中包含一些逻辑,以检查文件和配置位置的层次结构,以查看是否有可用于确定要实例化的实现类——例如,

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

    我希望能够做到这一点而不需要注入任何参考 ServletConfig 或者类似于我的工厂的任何东西——代码应该能够在servlet容器外正常运行。

    这听起来可能有点不寻常,但我希望这个组件能够与我们的一个webapps打包,并且具有足够的通用性,能够与我们的一些命令行工具打包,而不需要为我的组件提供新的属性文件,所以我希望能够在其他配置文件的基础上CH作为Web.xml。

    如果我没记错,.net有点像 Request.GetCurrentRequest() 获取对当前正在执行的 Request 但是,因为这是一个Java应用程序,所以我正在寻找一些可以用来访问 ServLL配置文件 .

    3 回复  |  直到 17 年前
        1
  •  5
  •   toolkit    17 年前

    一种方法是:

    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;
        }
    }
    

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

    <listener>
        <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>
    </listener>
    

    如果应用程序在Web容器中运行,那么在创建上下文后,容器将调用侦听器。在这种情况下,_servletContextProperties将替换为web.xml中指定的任何上下文参数。

    如果您的应用程序在Web容器外运行,那么servletContextProperties将为空。

        2
  •  1
  •   Tim Howland    17 年前

    您是否考虑过为此使用Spring框架?这样,您的bean就不会得到任何额外的损坏,Spring会为您处理配置设置。

        3
  •  0
  •   stjohnroe    17 年前

    我认为您必须添加一个相关的引导程序类,它引用servletconfig(或servletcontext),并将这些值转录到工厂类。至少这样你可以把它分开包装。

    @工具箱:非常好,非常谦虚-这是我一直在努力做的事情。