如何将.properties文件中的值包含到web.xml中?

时间:2012-08-23 19:53:50

标签: java-ee jboss web.xml java-ee-5

我需要将file.properties中的一些值包含在WEB-INF/web.xml这样的内容中:

<param-name>uploadDirectory</param-name>
<param-value>myFile.properties['keyForTheValue']</param-value>

我目前正在处理这个问题:

  • 的JBoss
  • JEE5

3 个答案:

答案 0 :(得分:13)

您可以添加此类,将文件中的所有属性添加到JVM。并将此类添加为上下文侦听器web.xml

public class InitVariables implements ServletContextListener
{

   @Override
   public void contextDestroyed(final ServletContextEvent event)
   {
   }

   @Override
   public void contextInitialized(final ServletContextEvent event)
   {
      final String props = "/file.properties";
      final Properties propsFromFile = new Properties();
      try
      {
         propsFromFile.load(getClass().getResourceAsStream(props));
      }
      catch (final IOException e)
      {
          // can't get resource
      }
      for (String prop : propsFromFile.stringPropertyNames())
      {
         if (System.getProperty(prop) == null)
         {
             System.setProperty(prop, propsFromFile.getProperty(prop));
         }
      }
   }
}  
web.xml中的

   <listener>       
      <listener-class>
         com.company.InitVariables
      </listener-class>
   </listener>  

现在您可以使用

获取项目中的所有属性
System.getProperty(...)

或在web.xml中

<param-name>param-name</param-name>
<param-value>${param-name}</param-value>

答案 1 :(得分:3)

关于上述已接受的解决方案,请注意。

我今天在jboss 5上试验过这个问题:contextInitialized()方法在加载web.xml之后才会被调用,因此对系统属性的更改不会及时生效。奇怪的是,这意味着如果重新部署webapp(不重新启动jboss),该属性将在上次部署时设置,因此它似乎可以正常工作。

我们将要使用的解决方案是通过java命令行将参数传递给jboss,例如-Dparameter1=value1 -Dparameter2=value2

答案 2 :(得分:0)

相关问题