Daniel Watrous
Daniel Watrous

Reputation: 3861

Tomcat web.xml configuration variables

My Java web application includes a configuration file (e.g. myapp.xml) in the war file. I provide the path to this file in my web.xml file as follows.

  <servlet>
    <servlet-name>wc</servlet-name>
    <servlet-class>com.myapp.servlets.WC</servlet-class>
    <init-param>
      <param-name>configfile</param-name>
      <param-value>${catalina.base}/webapps/myapp/WEB-INF/myapp.xml</param-value>
    </init-param>
  </servlet>

The problem is that I now want to deploy various versions on the same server for testing and development and each will have a different path under webapps. I want to avoid modifying the web.xml file for each deployment, but I can't find any way to reference the WEB-INF folder.

This is what I would like to do:

  <servlet>
    <servlet-name>wc</servlet-name>
    <servlet-class>com.myapp.servlets.WC</servlet-class>
    <init-param>
      <param-name>configfile</param-name>
      <param-value>${app.base}/myapp.xml</param-value>
    </init-param>
  </servlet>

Where ${app.base} == ${catalina.base}/webapps/myapp/WEB-INF

Is there some available variable that would give me the path to the application directory?

If not, can you think of some other way to accomplish this?

Upvotes: 3

Views: 8237

Answers (2)

Stefan
Stefan

Reputation: 12462

You can use

...
servletContext().getRealPath("");
...

to get the phyical main directory of you application.

Upvotes: 0

Bozho
Bozho

Reputation: 597382

You can pass the variable with -Dapp.base=/foo/bar to tomcat's JVM (depending on the version either in catalina.sh or in a file in /conf), and then read it with `System.getProperty(..) in your WC servlet.

Although it is advisable to put these configurations to an external location, so that you can change them without touching the deployed application, and also to enable unpacked WAR deployment, if needed.

If you want to access a resource within the application, then you'd better work with relative (rather than absolute) paths.

  • if the resource is on the classpath, use getClass().getResourceAsAstream(..)
  • if the resource is outside the classpath, use servletContext.getResourceAsStream(..)

Upvotes: 2

Related Questions