I am trying to port this CORS filter to JAX-RS 2.
However, I do not see how to get the Response object (as in the old code) from the ContainerResponseContext I get passed in the overridden method of ContainerResponseFilter.
If there is a more elegant way to do CORS with JAX-RS 2, that would be preferrable of course. Thanks in advance.
The Response class is an abstract class that contains three simple methods. The getEntity() method returns the Java object you want converted into an HTTP message body. The getStatus() method returns the HTTP response code. The getMetadata() method is a MultivaluedMap of response headers.
ok(). build(); } // return 404 to allow load balancers to only send traffic to the coordinator return Response. status(Response.Status.NOT_FOUND).
public abstract class Response extends Object. Defines the contract between a returned instance and the runtime when an application needs to provide meta-data to the runtime. An application class should not extend this class directly. Response class is reserved for an extension by a JAX-RS implementation providers.
Interface ContainerRequestContext. Container request filter context. A mutable class that provides request-specific information for the filter, such as request URI, message headers, message entity or request-scoped properties. The exposed setters allow modification of the exposed request-specific information.
Thre response is directly accessible as the ContainerResponseContext
:
@Provider
public class ResponseCorsFilter implements ContainerResponseFilter{
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders()
.putSingle("Access-Control-Allow-Origin","*");
responseContext.getHeaders()
.putSingle("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
List<String> reqHead=requestContext.getHeaders()
.get("Access-Control-Request-Headers");
if(null != reqHead){
responseContext.getHeaders()
.put("Access-Control-Allow-Headers",
new ArrayList<Object>(reqHead));
}
}
}
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