2008-09-03 110 views
4

是否有从豆或工厂类中不与Web容器相关联的所有Servlet API的web.xml中指定的访问属性(如初始化参数)以任何方式?有没有办法从Java Bean访问web.xml属性?

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

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

我希望能够做到这一点,而不会注入任何对ServletConfig或类似于我的工厂的任何参考 - 代码应该能够在Servlet容器外运行良好。

这可能听起来有点不寻常,但我希望我正在研究的这个组件能够与我们的一个web应用程序打包在一起,而且它还具有足够的多功能性,可以与我们的一些命令打包在一起在线工具不需要一个新的属性文件只为我的组件 - 所以我希望能搭载其他配置文件,如web.xml。

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

回答

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

然后在下面你的web.xml

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

如果您的应用程序在Web容器中运行,那么听者将由容器一旦环境已经创建调用。在这种情况下,_servletContextProperties将被替换为web.xml中指定的任何上下文参数。

如果你的应用运行在Web容器之外,那么_servletContextProperties将是空的。

1

你有没有考虑使用这个Spring框架?这样,你的豆没有得到任何额外的污点,并且弹簧为你处理配置设置。

0

我认为你必须添加一个相关的引导类将参考到的ServletConfig(或ServletContext中)和转录这些值的工厂类。至少这样你可以分开打包。

@toolkit:优秀,最卑微 - 这是我一直在尝试了一段时间,你可以做到这一点

相关问题