Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
Daniel Watrous Avatar asked May 01 '26 12:05

Daniel Watrous


1 Answers

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(..)
like image 80
Bozho Avatar answered May 03 '26 02:05

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!