May 14, 2017

How to handle Configuration in Tomcat with Context

Background

In Tomcat there seems no way to handle war deployment with version number in file name.

"When autoDeploy or deployOnStartup operations are performed by a Host, the name and context path of the web application are derived from the name(s) of the file(s) that define(s) the web application. Consequently, the context path may not be defined in a META-INF/context.xml embedded in the application and there is a close relationship between the context name, context path, context version and the base file name (the name minus any .war or .xml extension) of the file." [https://tomcat.apache.org/tomcat-8.0-doc/config/context.html]

So in your maven pom, you need to set <build><finalName>${project.artifactId}</finalName>...</build>.

Context Configuration

The context.xml can be placed:

  • $CATALINA_BASE/conf/[enginename]/[hostname]/[your_war_file_name].xml, e.g. $CATALINA_BASE/Catalina/localhost/example-tomcat.xml. Only visible inside example-tomcat.war.
  • $CATALINA_BASE/conf/context.xml. Global visible.
  • [your_war_file]/META-INF/context.xml. Deployed in your war file. This is not suited for configurable values.

The only sensible alternative of the above is the first. This is also good for RPM, since each application have a separate configuration file and no file collision from different RPM.

A little note about the path $CATALINA_BASE/conf/[enginename]/[hostname]/. If you look at your $CATALINA_BASE/conf/server.xml file, you see where [enginename] and [hostname] come from.

<?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">

    ...
    <Service name="Catalina">

        ...
        <Engine name="Catalina" defaultHost="localhost">

            <Host name="localhost" appBase="webapps" unpackWARs="true"
                autoDeploy="true">

                ...
            </Host>
        </Engine>
    </Service>
</Server>

More Configuration in Context

You can also put general configuration in you Context.

 <Context>
      ...
     <Parameter name="companyName" value="My Company, Incorporated"
          override="false"/>
       ...
 </Context>

   This is equivalent to the inclusion of the following element in the web application deployment descriptor (/WEB-INF/web.xml):

 <context-param>
       <param-name>companyName</param-name>
       <param-value>My Company, Incorporated</param-value>
 </context-param>

And retrieve it by

ServletContext sc = getServletContext();  
String companyName = sc.getInitParameter("companyName"); 

No comments: