If you are using Java EE to expose a RESTful API, it means that you are using JAX-RS - > Jersey, RestEasy or one of its implementations .
JAX-RS allows you to create generalizations for these cases. Mind you, you should be using version 2.0 at least
That interceptor of the speaker is called in this case ContainerResponseFilter
. Let's see an example:
1. we created the filter CORS
package su.estructura.de.paquetes;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
public class CORSResponseFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");
}
}
2.
We must register the new filter in the app, this depends on the configuration you have.
A. If you use JAX-RS together with javax.ws.rs.core.Application:
It's as simple as adding @Provider
to your filter, the rest is done by the framework ..
@Provider
public class CORSResponseFilter implements ContainerResponseFilter {}
B. ** If you have used Jersey as the implementation to JAX-RS ** and you have overwritten any of the methods of ResourceConfig
or Application
to register your clases,singletons,etc.
There will be register it manually:
package su.estructura.de.paquetes;
import org.glassfish.jersey.server.ResourceConfig;
public class RESTBootstrap extends ResourceConfig {
public RESTBootstrap(){
register(CORSResponseFilter.class);
packages("paquetes.que.se", "van.a.escanear");
}
}
It's pretty simple, I hope it's helpful.