我想控制web.xml中的設置,並針對不同的環境使用不同的設置。在web.xml中使用屬性
是否可以在web.xml中使用類路徑上的屬性文件的屬性?事情是這樣的:
<context-param>
<param-name>myparam</param-name>
<param-value>classpath:mypropertyfile.properties['myproperty']</param-value>
</context-param>
問候
P
我想控制web.xml中的設置,並針對不同的環境使用不同的設置。在web.xml中使用屬性
是否可以在web.xml中使用類路徑上的屬性文件的屬性?事情是這樣的:
<context-param>
<param-name>myparam</param-name>
<param-value>classpath:mypropertyfile.properties['myproperty']</param-value>
</context-param>
問候
P
不,但您可以在運行時將屬性文件傳入並從中讀取。
<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");
我的myprop.properties文件應該放在項目文件夾層次結構中? – Amruta 2014-11-25 20:02:50
如果您正在嘗試配置不受您設計控制的第三方組件,這並不重要。 – 2017-08-31 17:26:55
AFAIK context-param
和env-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構建過程的一部分。
如果使用不同的環境,很可能在運行時不會從一個切換到另一個,因此不需要使用屬性文件。
如果使用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>
這裏配置過濾是解決方案: http://stackoverflow.com/questions/12099008/how-to-include-values-from-properties-file-into-web-xml/12099830#12099830 – lancha90 2012-08-23 21:18:44