Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Response in ContainerResponseFilter's (JAX-RS 2)

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.

like image 554
Janus Troelsen Avatar asked Jul 26 '13 11:07

Janus Troelsen


People also ask

How do you return a response in Java?

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.

What is response OK () build ()?

ok(). build(); } // return 404 to allow load balancers to only send traffic to the coordinator return Response. status(Response.Status.NOT_FOUND).

What is Response in Java?

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.

What is ContainerRequestContext in Java?

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.


1 Answers

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));
           }
    }

}
like image 169
Carlo Pellegrini Avatar answered Nov 14 '22 22:11

Carlo Pellegrini