2010-06-01 59 views
9

我想控制web.xml中的设置,并针对不同的环境使用不同的设置。在web.xml中使用属性

是否可以在web.xml中使用类路径上的属性文件的属性?事情是这样的:

<context-param> 
    <param-name>myparam</param-name> 
    <param-value>classpath:mypropertyfile.properties['myproperty']</param-value> 
</context-param> 

问候

P

+2

这里配置过滤是解决方案: http://stackoverflow.com/questions/12099008/how-to-include-values-from-properties-file-into-web-xml/12099830#12099830 – lancha90 2012-08-23 21:18:44

回答

6

不,但您可以在运行时将属性文件传入并从中读取。

<context-param> 
    <param-name>propfile</param-name> 
    <param-value>myprop.properties</param-value> 
</context-param> 

然后,如果您有权访问servlet,那么在运行时加载属性将变得很简单。

Properties properties = new Properties(); 
GenericServlet theServlet = ...; 
String propertyFileName = theServlet.getInitParameter("propfile"); 
properties.load(getClass().getClassLoader().getResourceAsStream(propertyFileName)); 
Object myProperty = properties.get("myProperty"); 
+1

我的myprop.properties文件应该放在项目文件夹层次结构中? – Amruta 2014-11-25 20:02:50

+0

如果您正在尝试配置不受您设计控制的第三方组件,这并不重要。 – 2017-08-31 17:26:55

2

AFAIK context-paramenv-entry都保持静态值。您不会从属性文件中获取运行时(动态)值。 它会像:

<context-param>  
    <param-name>myparam</param-name>  
    <param-value>myactualpropertyvalue</param-value>  
</context-param> 

任何变化的值需要的Web应用程序的重新部署。

在你的榜样,您检索会classpath:mypropertyfile.properties['myproperty']

如果使用Glassfish的,你可以更新它从命令行http://javahowto.blogspot.com/2010/04/glassfish-set-web-env-entry.html

飞如果我理解你的要求是在生成时的字符串值(即不同的战争对于不同的env)而不是在运行时间?

您可以将web.xml中的值替换为ant/maven构建过程的一部分。

+2

感谢您的回复。不过,我想在启动时寻找该物业。即同一场战争对不同的环境应该有不同的属性。我不确定是否有可能做到这一点。 目前我所做的几乎和你所建议的一样,我在Maven构建过程中替换了这个值。 – 2010-06-03 11:00:38

+0

这是信息... http://java.sun.com/developer/technicalArticles/xml/WebAppDev4/ – ingyhere 2012-03-22 23:17:30

+0

你会如何在Java代码中调用该上下文? 'classpath'指向哪里? – JesseBoyd 2017-09-08 20:48:12

1

如果使用不同的环境,很可能在运行时不会从一个切换到另一个,因此不需要使用属性文件。

如果使用maven,则可以为您的环境定义不同的配置文件,并在每个配置文件中设置要更改的参数。

在你的pom.xml

<profile> 
    <id>env1</id> 
    <properties> 
     <my.param>myParamValue<my.param/> 
    </properties> 
</profile> 

<profile> 
    <id>env2</id> 
    <properties> 
     <my.param>myParamValue2<my.param/> 
    </properties> 
</profile> 

在web.xml

<context-param> 
    <param-name>myparam</param-name> 
    <param-value>${my.param}</param-value> 
</context-param> 

而且在部署描述符中的Maven插件战争

<plugin> 
    <groupId>org.apache.maven.plugins</groupId> 
    <artifactId>maven-war-plugin</artifactId> 
    <configuration> 
     <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors> 
    </configuration> 
</plugin> 
相关问题