2
votes

I am struggling to setup an embedded Tomcat server. The setup I have is not similar to the Tomcat convention, as I have a somePath/www directory, where my static files including index.html are. I also don't have WEB-INF and I don't have web.xml.

I need Tomcat to open index.html when requesting localhost:8080/. This does not work and I get a page being not found error. Nevertheless when I request localhost:8080/index.html the request returns the relevant file. My current current attempted configuration is shown below.

tomcat.addWebapp("/", "somePath/www");
Context ctx = tomcat.addContext("/", "somePath/www");
Wrapper defaultServlet = ctx.createWrapper();
defaultServlet.setName("default");
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listings", "false");
defaultServlet.setLoadOnStartup(1);
ctx.addChild(defaultServlet);
ctx.addServletMapping("/*", "default");

On the other hand, for the following setup:

tomcat.addWebapp("/MY_APP", "somePath/www");

localhost:8080/MY_APP/ works fine too.

Is there a way to have embedded Tomcat load index.html located in an arbitrary directory, when the url is just the context root? I also require the solution to not change the directory structure. Thanks!

1

1 Answers

3
votes

In order for tomcat to serve index.html on requests with just the context path (http://localhost:8080/) you need to apply the following modifications:

  • Add "index.html" to the list of welcome files of your context using Context.addWelcomeFile(). The file will be looked up relative to your context's base directory. You can also use relative paths, eg. "static/index.html"
  • Use "/" pattern in servlet mapping for "default" servlet. Only then tomcat will consider welcome files and rewrite the request path before calling default servlet.

After applying these changes the code should look like this:

Context ctx = tomcat.addContext("/", "somePath/www");

defaultServlet = ctx.createWrapper();
defaultServlet.setName("default");
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listings", "false");
defaultServlet.setLoadOnStartup(1);

ctx.addChild(defaultServlet);
ctx.addServletMapping("/", "default");
ctx.addWelcomeFile("index.html");

This is similar to how tomcat configures the context when you call tomcat.addWebapp(), so you could just use this:

Context ctx = tomcat.addWebapp("/", "somePath/www");