I need to configure my Jetty server so that it can serve static HTML files from one project and REST responses from a second project however I can only seem to get the REST side to work...
I have a project structure similar to:
+-project-core
| +-src/main/java/jetty/JettyRunner.java
|
+-project-web
| +-src/main/webapp/static/index.html
|
+-project-REST
+-src/main/java/resource/RestResource.java
My JettyRunner sets up a Server like:
// REST (JERSEY 2.0 stuff)
WebAppContext restHandler = new WebAppContext();
restHandler.setResourceBase("./");
restHandler.setParentLoaderPriority(true);
restHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
ServletHolder restServlet = restHandler.addServlet(ServletContainer.class, "/rest/*");
restServlet.setInitOrder(0);
restServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "resource");
restServlet.setInitParameter("useFileMappedBuffer", "false");
// Web - note I can't use a ResourceHandler because it doesn't allow the init param I require below
WebAppContext webHandler = new WebAppContext();
webHandler.setResourceBase("../project-web/src/main/webapp/static");
webHandler.setInitParameter("useFileMappedBuffer", "false");
webHandler.setWelcomeFiles(new String[]{"index.html"});
// Server
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(webHandler);
handlers.addHandler(restHandler);
Server server = new Server(8080);
server.setHandler(handlers);
server.start();
The REST side of things seems to work fine, I can hit localhost:8080/rest/someendpoint
which returns a 200
but when I hit localhost:8080
I get a directory structure of project-core
and not the index.html file I was expecting. If I hit localhost:8080/index.html
I get a 404
. What am I doing wrong?
Already answered in Serving Static Files from Alternate Path in Embedded Jetty.
You don't want another WebAppContext
, just add another specific DefaultServlet
on your original WebAppContext
.
Note:
WebAppContext.addServlet()
does exist.WebAppContext
extendsServletContextHandler
as seen in the other answer.