我想有一个(嵌入式)jetty + jersey服务器,它提供REST api(“/ resource”路由上的GET和POST),但也提供一些静态内容(index.html,bundle.js on the“ /“)。我只能让/ resource部分工作 - 用curl测试GET / POST,即
curl -X POST -H 'Content-Type: application/json' -d '{"resource":"FOOBAR"}' http://localhost:8080/resource
然而,“/”路径通过此设置返回404:
public static void main(String[] args) {
Server jettyServer = new Server(8080);
ResourceConfig rc = new ResourceConfig();
JSONResource resource = new JSONResource();
rc.register(resource);
ServletContainer sc = new ServletContainer(rc);
ServletHolder servletHolder = new ServletHolder(sc);
// ServletHolder servletHolder = new ServletHolder("default", new DefaultServlet());
// static content
servletHolder.setInitParameter("resourceBase", "./src/webapp/");
ServletContextHandler context = new ServletContextHandler();
context.addServlet(servletHolder, "/*");
jettyServer.setHandler(context);
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
路径:
@Path("/resource")
public class JSONResource {
Resource resource = Resource.getInstance();
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getStringResource() {
return this.resource;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response putStringResource(Resource json) {
this.resource.setResource(json.getResource());
return Response.status(Status.OK).entity(json).build();
}
}
资源类的完整性:
public class Resource {
private String resource = "";
private Resource() {
}
private static class Holder {
private static final Resource INSTANCE = new Resource();
}
public static Resource getInstance() {
return Holder.INSTANCE;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public String toString() {
return resource;
}
}
编辑了以下每个答案
// ---JSON RESOURCE---//
JSONResource resource = new JSONResource();
ResourceConfig rc = new ResourceConfig();
rc.register(resource);
ServletContainer sc = new ServletContainer(rc);
ServletHolder servletHolder = new ServletHolder(sc);
ServletContextHandler jsonResourceContext = new ServletContextHandler();
jsonResourceContext.addServlet(servletHolder, "/*");
// ---STATIC RESOURCE---//
ResourceHandler staticResourceHandler = new ResourceHandler();
staticResourceHandler.setResourceBase("./src/webapp/");
ContextHandler staticContextHandler = new ContextHandler("/");
staticContextHandler.setHandler(staticResourceHandler);
// ---ADD HANDLERS---//
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { jsonResourceContext, //
staticContextHandler, //
new DefaultHandler() //
});
jettyServer.setHandler(handlers);
可以减少冗长吗?
答案 0 :(得分:1)
您的服务器类只有一个静态内容处理程序。你需要一个额外的JSON东西处理程序。必须将其分配给处理程序列表。
e.g。
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { jsonRessourcehandler, servletContextHandler, new DefaultHandler() });
server.setHandler(handlers);
还提供类似json的东西,你想要搜索JERSEY库/例子