我正在尝试创建一个具有REST API的Web服务,并且可以提供静态html等文档。目前我已经让REST(Jersey 2.17)api工作正常,但我很难提供资源,比如我的index.html
项目结构
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();
}
}
点击localhost:8315/rest/someRestEndpoint
工作正常,但如果我尝试点击localhost:8315
,当我期待index.html
欢迎文件时,我会得到一个目录结构。我究竟做错了什么?
注意我没有使用WEB.XML,因为我正在尝试在上面的类中进行所有配置。
依赖关系(如果有帮助)(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}"
答案 0 :(得分:1)
事实证明,请求按照它们添加到集合的顺序被分派给处理程序,restHandler
必须设置响应才能完成。因此,请求从未进入webHandler
,并且欢迎文件从未添加到响应中。此外,ResourceHandler
正在查找index.html的基本目录,将resourceBase
设置为src/main/webapp
修复此问题。