3

Apparently, ResourceHandler stop hosting files with jetty 9 - 404 not found error (works fine with jetty 8). Here is the code:

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setResourceBase("some_resource_base");

    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[]{servletHandler, resourceHandler});
    server.setHandler(handlerList);
    server.start();

This quistion with the accepted answer does not seem to work against jetty 9 - Serving static files w/ embedded Jetty

Community
  • 1
  • 1
Ilya Buziuk
  • 1,839
  • 5
  • 27
  • 43

2 Answers2

4

In case somebody is looking for a working example, this is how I combined a ResourceHandler with a ContextHandler (partially based on current Jetty docs: Jetty documentation)

        srv = new Server();
        ServerConnector srvConn = new ServerConnector(srv);
        srvConn.setHost("localhost");
        srvConn.setPort(8080);
        srvConn.setIdleTimeout(30000);
        srv.addConnector(srvConn);
        //used for webSocket comm later:
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        //for static  content:
        ResourceHandler resH = new ResourceHandler();
        resH.setDirectoriesListed(true);
        resH.setWelcomeFiles(new String[]{ "index.html" });
        resH.setResourceBase("./my/web/root");
        ContextHandler resCtx = new ContextHandler();
        resCtx.setHandler(resH);

        //Add both ContextHandlers to server:
        ContextHandlerCollection handlers = new ContextHandlerCollection(resCtx, context);
        srv.setHandler(handlers);
Max F
  • 71
  • 5
3

Assuming that servletHandler is a ServletContextHandler

(Note: it best not be an actual ServletHandler, as that's an internal class, not meant to be instantiated directly)

Then 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.

Joakim Erdfelt
  • 46,896
  • 7
  • 86
  • 136
  • This is what I was looking for. Hopefully, it will help a others on this thread too.. Thanks Joakim. http://stackoverflow.com/questions/20207477/serving-static-files-from-alternate-path-in-embedded-jetty/20223103#20223103 – Jay Khatwani Nov 20 '16 at 23:43