I'm trying to create a web service that has a REST API and can serve documents such as static html. At the moment I've got the REST (Jersey 2.17) api working fine but I'm struggling to serve up resources such as my index.html
Project Structure
src
--main
----java
------resource
--------RestResource.java
------app
--------LocalRunner.java
----webapp
------index.html
LocalRunner.java
public class LocalRunner {
private final Server server;
public LocalRunner() {
server = new Server(8315);
}
public void start() throws Exception {
// REST
WebAppContext restHandler = new WebAppContext();
restHandler.setResourceBase("./");
restHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
ServletHolder restServlet = restHandler.addServlet(ServletContainer.class, "/rest/*");
restServlet.setInitOrder(0);
restServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "resource");
// Web
ResourceHandler webHandler = new ResourceHandler();
webHandler.setResourceBase("./");
webHandler.setWelcomeFiles(new String[]{"index.html"});
// Server
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(restHandler);
handlers.addHandler(webHandler);
server.setHandler(handlers);
server.start();
}
public static void main(String[] args) throws Exception {
new LocalRunner().start();
}
}
Hitting localhost:8315/rest/someRestEndpoint
works fine but if I try hit just localhost:8315
I get a directory structure when I'm expecting my index.html
welcome file. What am I doing wrong?
Note I am not using a WEB.XML as I'm trying to do all the configuration in the class above.
Dependencies if it helps (Gradle)
def jettyVersion = '7.2.2.v20101205';
compile "org.eclipse.jetty:jetty-server:${jettyVersion}"
compile "org.eclipse.jetty:jetty-webapp:${jettyVersion}"
compile "org.eclipse.jetty:jetty-servlet:${jettyVersion}"
def jerseyVersion = '2.17'
compile "org.glassfish.jersey.core:jersey-server:${jerseyVersion}"
compile "org.glassfish.jersey.containers:jersey-container-servlet-core:${jerseyVersion}"
It turns out the request is dispatched to the Handlers in the order they are added to the collection and the
restHandler
must have been setting the response to complete. As a result the request never made it to thewebHandler
and the welcome file was never added to the response. Also theResourceHandler
was looking in the base directory for the index.html, setting theresourceBase
tosrc/main/webapp
fixed this.