Tomcat embedded correct usage of addContext for docBase

Jimmy Johnson picture Jimmy Johnson · Jan 29, 2013 · Viewed 7.8k times · Source

Does anyone know how to set up the context in an embedded Tomcat instance to serve files from a local directory not within the deployed folder?

In the standard server.xml it looks something like this:

<Context docBase="/MyWebApp/images" path="/tmp/images/" reloadable="false"/>

I have tried different variations on the following tomcat embedded call without success:

tomcat.addContext(tomcat.getHost(), "/MyWebApp/images", "/tmp/images/");

I also tried:

tomcat.addContext("/MyWebApp/images", "/tmp/images/");

It looks like this grails question was along the same lines:

grails: add context to embedded tomcat in development

But im not using grails. (Using Java)

Here is the full startup code I am using:

package launch;

import java.io.File;
import org.apache.catalina.startup.Tomcat;

public class Main {

    public static void main(String[] args) throws Exception {

        String webappDirLocation = "/src/main/webapp/";
        Tomcat tomcat = new Tomcat();

        //The port that we should run on can be set into an environment variable
        //Look for that variable and default to 8080 if it isn't there.
        String webPort = System.getenv("PORT");
        if(webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        tomcat.setPort(Integer.valueOf(webPort));

        tomcat.addWebapp("/MyWebApp", new File(webappDirLocation).getAbsolutePath());
        tomcat.addContext("/MyWebApp/images", "/tmp/images/");

        tomcat.start();
        tomcat.getServer().await();  
    }
}

Answer

Mark Thomas picture Mark Thomas · Feb 3, 2013

There are two general approaches to adding web applications to embedded Apache Tomcat. addContext() and addWebapp().

addContext() requires a fully programmatic approach. You must configure everything via the API. That includes the default servlet which serves static content (like images). You have not configured the default Servlet hence no static content is served.

You almost certainly want to use addWebapp() which is broadly similar to dropping a directory in the webapps folder and having Tomcat auto-deploy it. Settings equivalent to the those in conf/web.xml (default servlet, JSP servlet, MIME type mappings, welcome files, etc) will be applied to the webapp in this case.