【问题标题】:How to use context-param defined in web.xml in dispatcher servlet?如何在调度程序 servlet 中使用 web.xml 中定义的上下文参数?
【发布时间】:2013-02-23 19:28:58
【问题描述】:

我有一个非常小的问题,即使在谷歌上搜索了很长一段时间后我也找不到答案。

我们如何在dispatcher servlet中使用web.xml中定义的context-param?

在我的 web.xml 中,我是这样定义的:

<context-param>
    <param-name>root.path</param-name>
    <param-value>/root</param-value>
</context-param>

我可以使用以下代码行在我的 Java 类中访问它:

String rootPath = sce.getServletContext().getInitParameter("root.path");

但是,我看不到在调度程序 servlet 中使用此值的方法。在以下情况下,我想为 /root 使用一个变量而不是值本身。

<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="file:/root/main.properties" />

非常感谢任何帮助。

谢谢。

【问题讨论】:

  • 我有一个问题。这个上下文参数解决了什么目的?取而代之的是,您可以在环境变量中的任何位置或其他地方将此变量外部化。在这里,您在一个地方声明变量,而在另一个地方您正在引用它。两者都是内部的地方,不像外部化。
  • 我觉得求助于环境变量不是很好。出于安全原因(用于存储密码等),我想将我的属性文件保留在类路径之外,并且会在多个地方引用它。所以我打算定义一个上下文变量并在其他配置xmls中使用它。
  • 我想再提一个建议。您应该在属性文件中保留“root.path”的值,然后决定从哪里选择它

标签: spring servlets properties


【解决方案1】:

尝试使用

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="file:/#{contextParameters.root.path}/main.properties" />

如果我们将名称命名为“root.path”,而不是将名称命名为“root_path”,则会产生问题

【讨论】:

  • 太棒了!它就像一个魅力。在网上搜索了数小时后,我在任何地方都没有看到这种用法。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-05-10
  • 2015-05-19
  • 2010-12-10
  • 1970-01-01
  • 2013-02-27
  • 2016-10-25
  • 1970-01-01
相关资源
最近更新 更多