【问题标题】:Can you read a java property in web.xml?你能读取 web.xml 中的 java 属性吗?
【发布时间】:2011-02-26 07:11:07
【问题描述】:

我想控制 web.xml 中的设置,并为不同的环境使用不同的一次。

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

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

最好的问候

P

【问题讨论】:

标签: web-applications properties web.xml


【解决方案1】:

AFAIK context-paramenv-entry 都保存静态值。您不会从属性文件中获取运行时(动态)值。 会是这样的:

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

对值的任何更改都需要重新部署网络应用程序。

在您的示例中,您检索的值将是字符串 classpath:mypropertyfile.properties['myproperty']

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

如果我了解您的要求是在构建时(即不同环境的不同战争),而不是在运行时?

您可以在 ant/maven 构建过程中替换 web.xml 中的值。

【讨论】:

  • 感谢您的回复。但是,我想在启动时寻找该属性。 IE。对于不同的环境,同一个战争应该有不同的属性。我不确定是否有可能做到这一点。目前我几乎按照你的建议做,我正在 Maven 构建期间替换值。
  • 如何在 Java 代码中调用该上下文? 'classpath' 指向哪里?
【解决方案2】:

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

<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 文件应该在项目文件夹层次结构中的什么位置?
  • 如果您尝试配置您无法控制其设计的第三方组件,这并非易事。
【解决方案3】:

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

如果使用 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 war 插件的部署描述符中配置过滤

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

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多