Serving static files with embedded Jetty

In my small web server I have two files, a index.html and a info.js locate under /src/webapp and I want them to be served from the embedded jetty web server.

This is how I solve the problem with static content.

Server server = new Server(8080);

ServletContextHandler ctx = new ServletContextHandler();
ctx.setContextPath("/");

DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
holderPwd.setInitParameter("resourceBase", "./src/webapp/");

ctx.addServlet(holderPwd, "/*");
ctx.addServlet(InfoServiceSocketServlet.class, "/info");

server.setHandler(ctx);

Worked like a charm!


There is an important difference between serving static content using a ResourceHandler and using a DefaultServlet (with a ServletContextHandler).

When a ResourceHandler (or a HandlerList holding multiple ResourceHandler instances) is set as a context handler, it directly processes requests and ignores any registered javax.servlet.Filter instances.

If you need filters, the only way to go about it is using a ServletContextHandler, adding filters to it, then adding a DefaultServlet and finally, setting the base Resource.

The base Resource represents a resourceBase path a ResourceHandler would be initialised with. If serving static resources from multiple directories, use a ResourceCollection (which is still a Resource) and initialise it with an array of resourceBase strings:

ResourceCollection resourceCollection = new ResourceCollection();
resourceCollection.setResources(getArrayOfResourceBaseDirs());

Use a ResourceHandler instead of ServletContextHandler.