简体   繁体   中英

Serve both Thrift/TServlet and static files from same Jetty server

I'm trying to serve static files and a Thrift service from the same Jetty server. Up until now I have the following code:

val server = new Server();
val connector = new SelectChannelConnector();
connector.setPort(4567);
server.addConnector(connector);

val servlet_handler = new ServletContextHandler(server,"/thrift",ServletContextHandler.SESSIONS);
servlet_handler.addServlet(new ServletHolder(new SomeThriftServlet()), "/thrift/*");

val resource_handler = new ResourceHandler();
resource_handler.setWelcomeFiles(new String[]{ "index.html" });
resource_handler.setResourceBase(".");

val handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, servlet_handler, new DefaultHandler() });
server.setHandler(handlers);

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

The static files are served just fine, but the Thrift service keeps giving me 404 errors. What am I doing wrong?


Note : the code to serve static files was taken from this question , and the 'val' types are taken care of by project lombok , but I left them in there because I think the current code is more readable.

The crux of the problem is that you have to wrap the ResourceHandler in its own context, and then give the two (or more) contexts their own base path. This is because a ResourceHandler has no base path of it's own.

After this, you can provide the contexts to the server in a ContextHandlerCollection , which determines which context to use based on the longest matching path prefix.

Server server = new Server();

val connector = new SelectChannelConnector();
connector.setPort(4567);
server.addConnector(connector);

val thr = new SomeThriftServlet();

val ct0 = new ServletContextHandler(ServletContextHandler.SESSIONS);
ct0.setContextPath("/thr");
ct0.addServlet(new ServletHolder(thr), "/*");

val rsc = new ResourceHandler();
rsc.setDirectoriesListed(true);
rsc.setWelcomeFiles(new String[]{ "index.html" });
rsc.setResourceBase(".");

val ct1 = new ContextHandler();
ct1.setContextPath("/rsc");
ct1.setHandler(rsc);

val contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] {ct0, ct1, new DefaultHandler() });

server.setHandler(contexts);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM