To enable cross-origin requests in a self-contained Jetty jar file with Jersey REST services (to allow calls from Swagger-UI).
Create a
CORSResponseFilter
class:
public class CORSResponseFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
MultivaluedMap headers = responseContext.getHeaders();
headers.add("Access-Control-Allow-Origin", "*");
//headers.add("Access-Control-Allow-Origin", "http://podcastpedia.org"); //allows CORS requests only coming from podcastpedia.org
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");
}
}
And reference it in your main
App
class:
public class App {
public static void main(String[] args) throws Exception {
URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
ResourceConfig config = new ResourceConfig(API.class);
config.register(CORSResponseFilter.class);
Server jettyServer = JettyHttpContainerFactory.createServer(baseUri, config);
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
No comments:
Post a Comment