【问题标题】:How to set value in web.xml using property file?如何使用属性文件在 web.xml 中设置值?
【发布时间】:2011-03-16 01:55:25
【问题描述】:
我想知道是否可以使用属性文件在web.xml 中设置属性。例如 web.xml:
<context-param>
<param-name>Map.MyJNDI</param-name>
<param-value>java:comp/env/jdbc/${my.computer}</param-value>
</context-param>
而application.properties 将是:
# My computer's name
my.computer=eniac
【问题讨论】:
标签:
java
servlets
properties
web.xml
【解决方案1】:
你不能像这样在 web.xml 中替换值。
如果可能的话,我可以建议一个选项,只要有一个带有占位符的模板 web.xml 用于值,并且在构建每个环境期间都有一个构建过程中的步骤,它将替换该环境所需属性文件中的所需值。
【解决方案2】:
您不能从Properties 文件中设置值,但您可以设置属性文件并在运行时读取它。
<context-param>
<param-name>propfile</param-name>
<param-value>myproject.properties</param-value>
</context-param>
然后在运行时读取属性文件。
MyServlet myServlet = new MyServlet();
Properties properties = new Properties();
// get the properties file name
String propfile = myServlet.getInitParameter("propfile");
// load the file
properties.load(getClass().getClassLoader().getResourceAsStream(propfile));
// get the desire properties
Object propName = properties.get("my.computer");
// out.println(propName.toString());
希望这对其他人也有帮助。