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
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.
Your code doesn't work because a ContextHandler
doesn't actually server up content.
A small adjustment will make it sort of work, but to do what you really want you'll need to write your own handler.
The "sort of works" version:
ContextHandler capHandler = new ContextHandler();
capHandler.setContextPath("/clientaccesspolicy.xml");
ResourceHandler resHandler = new ResourceHandler();
resHandler.setBaseResource(Resource.newClassPathResource("clientaccesspolicy.xml"));
capHandler.setHandler(resHandler);
But, that version treats /clientaccesspolicy.xml
as a directory, so it redirects to /clientaccesspolicy.xml/
and then displays the contents of the XML file.
What it looks like you want is a version of the ResourceHandler
that has a lookup of url => resource.
Jetty doesn't ship with a handler that does that, but you should be able to create a subclass of ResourceHandler
and then override getResource
. In that case you won't need [or want] the ContextHandler, just check for calls to "/clientaccesspolicy.xml" and map it to the correct ClassPath Resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With