What is difference between ServletContextHandler.setResourceBase and ResourceHandler.setResourceBase when using Jetty embedded container?

With that setup, the resourceHandler will never be called, as the DefaultServlet processing (or Default404Servlet) at the end of the ServletContextHandler chain will always respond, not allowing resourceHandler to even execute.

If you have a ServletContextHandler, do not use ResourceHandler use the DefaultServlet in that ServletContextHandler to setup and serve your static files.

ResourceHandler is very simplistic, if you want more control / features, use a DefaultServlet configured in your ServletContextHandler instead.

Ok, with that out of the way …

The ServletContextHandler.setBaseResource(Resource) is the place for the ServletContext itself to configure its context-wide resourceBase.

(Note: the parameter of setResourceBase() is a URL string that can point to a file:// directory or even a jar:file:// location. Pretty much anything supported by Resource.newResource(String))

  • ${resourceBase}/ is the lookup point for various methods in javax.servlet.ServletContext such as:
    • String getRealPath(String path)
    • URL getResource(String path)
    • InputStream getResourceAsStream(String path)
    • Set<String> getResources(String path)
  • Requested resources that don’t match any of your servlets or filters, will then be handled by the DefaultServlet, which might serve static resources (such as *.html, *.css, *.js) from the specified ${resourceBase}/${request.pathInfo}

ResourceHandler does not participate in ServletContextHandler is an is inappropriate to mix with ServletContextHandler.

Also, don’t forget to set ServletContextHandler.setContextPath(String) to your desired context path (usually "https://stackoverflow.com/")

And yes, you can even have multiple DefaultServlet configurations in a single ServletContextHandler.

Leave a Comment