如何使用属性文件在web.xml中设置值?

Tom*_*bic 9 java web.xml servlets properties

我想知道是否有可能web.xml通过使用属性文件设置属性.例如web.xml:

<context-param>
  <param-name>Map.MyJNDI</param-name>
  <param-value>java:comp/env/jdbc/${my.computer}</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

并且application.properties将是:

# My computer's name
my.computer=eniac
Run Code Online (Sandbox Code Playgroud)

Nik*_*aul 2

您无法从Properties文件设置值,但可以设置属性文件并在运行时读取它。

<context-param>
    <param-name>propfile</param-name>
    <param-value>myproject.properties</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

然后在运行时读取属性文件。

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());
Run Code Online (Sandbox Code Playgroud)

希望这也能帮助其他人。