How can I serve a particular classpath resource at a given address using embedded jetty?

Andy picture Andy · Feb 2, 2012 · Viewed 7k times · Source

I'm looking to expose a clientacesspolicy.xml file from an embedded jetty server.

My current attempt looks like this:

ContextHandler capHandler = new ContextHandler();
capHandler.setContextPath("/clientaccesspolicy.xml");
capHandler.setBaseResource(Resource.newClassPathResource("clientaccesspolicy.xml"));
HandlerList handlers = new HandlerList();
handlers.addHandler(capHandler);
...
httpServer.setHandler(handlers);

But I get a 404 accessing http://localhost:9000/clientaccesspolicy.xml

How can I expose a classpath resource to a given URL programmatically in Jetty?

Thanks, Andy

Answer

Dariusz Starzyński picture Dariusz Starzyński · Jul 25, 2013

Actually, you can just register a class path as a class path resource (surprisingly).

ResourceHandler resHandler = new ResourceHandler();
resHandler.setBaseResource(Resource.newClassPathResource("/"));
server.setHandler(resHandler);

Then you can access whatever files are in your class path. So if you have a file.xml it will be served from localhost:9000/file.xml.