Skip to content Skip to sidebar Skip to footer

How To Get Embedded Jetty Serving Html Files From A Jar, Not A War

I have been searching without success in how to get an embedded jetty server to serve a handful of html files that are contained within the same jar. Surely this is possible? I re

Solution 1:

You need to set the Resource Base for the Context to the URL/URI to where your static content can be accessed from.

Note: you set this at the ServletContext level, not the DefaultServlet level, that way all servlets in your context have access to the same information and the various methods in ServletContext related to real file paths and resources are sane.

publicstaticvoidmain(String[] args)throws Exception
{
    Serverserver=newServer(8080);

    // Figure out what path to serve content fromClassLoadercl= MyEmbeddedJettyMain.class.getClassLoader();
    // We look for a file, as ClassLoader.getResource() is not// designed to look for directories (we resolve the directory later)URLf= cl.getResource("static-root/hello.html");
    if (f == null)
    {
        thrownewRuntimeException("Unable to find resource directory");
    }

    // Resolve file to directoryURIwebRootUri= f.toURI().resolve("./").normalize();
    System.err.println("WebRoot is " + webRootUri);

    ServletContextHandlercontext=newServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setBaseResource(Resource.newResource(webRootUri));
    context.setWelcomeFiles(newString[]{"welcome.html"});

    ServletHolderholderPwd=newServletHolder("default", DefaultServlet.class);
    holderPwd.setInitParameter("dirAllowed","true");
    context.addServlet(holderPwd,"/");

    server.setHandler(context);

    server.start();
    server.join();
}

Post a Comment for "How To Get Embedded Jetty Serving Html Files From A Jar, Not A War"