Search code examples
javacsstomcattomcat8

Tomcat custom context.xml file is never taken into account


I have currently a problem with the Tomcat configuration of a web application (I use Tomcat 8.5.57).
This web application is packaged in a war file containing, among others, html files and css files.
This application works well.

Now, I have a request from a customer asking to be able to modify the look and feel of the application from outside of the war via a custom css file managed by the client (used to set the logo of the client or stuff like that).
So I tried to create a custom context file, called custom.xml, that I placed in tomcat\conf\Catalina\localhost directory.
This file looks like :

<Context    docBase="E:/somedirectory/support" 
            path="/app/css" 
            reloadable    = "false"
            unpackWAR     = "false"
            swallowOutput = "true" >
                <WatchedResource>custom.css</WatchedResource>           
</Context>

I put the custom.css file containing some css instructions as test in the E:/somedirectory/support directory.
In the html file of my web application, I have the following line in the head section :

<link rel="stylesheet" href="css/custom.css" media="screen" type="text/css"/>

The problem is that my custom.css file is never taken into account.

When I open the Sources tab of Chrome's developer tools, I see a custom.css file in the hierarchy in app/css as expected (probably due to the line in the html file), but it is hopelessly empty.
I tried a lot of things found on the Web and on stackoverflow, but nothing worked for me...

Can someone help me ?

Thank you !


Solution

  • The path attribute of <Context> element is ignored outside of server.xml:

    This attribute must only be used when statically defining a Context in server.xml. In all other circumstances, the path will be inferred from the filenames used for either the .xml context file or the docBase. [from Tomcat documentation]

    Therefore you have two choices:

    • You can define a new context (new web application) with context path /app/css by creating a file named conf\Catalina\localhost\app#css.xml and content:
    <Context docBase="E:\somedirectory\support" />
    

    This way everything under the /app/css subtree will only be served from the E:\somedirectory\support directory.

    1. You can redefine your application context to include an additional virtual directory (beside the contents of the WAR file) by adding a file named conf\Catalina\localhost\app.xml with content:
    <Context>
      <Resources>
        <PreResources className="org.apache.catalina.webresources.DirResourceSet"
                      base="E:\somedirectory\support"
                      webAppMount="/css" />
      </Resources>
    </Context>
    

    This way, while serving a request for /app/css/foo/bar, Tomcat will first look for foo/bar in E:\somedirectory\support and then in the WAR file.