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

1

5

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.

Septivalent answered 26/7, 2013 at 11:43 Comment(0)
T
10

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

}
Thaxton answered 26/7, 2013 at 13:59 Comment(7)
But using this how can i get My response BODY ?Fango
There is the ContainerResponseContext.setEntity method which allows to substitute the entire entity.Thaxton
Thanks... can i do reverse operation on ContainerRequestContext ? I mean i want to get POJO from ContainerRequestContext in filter . from ContainerRequestContext, we can get EntityStream from that,but i want Entity as we get in ContainerResponseContextFango
There is ContainerResponseContext.getEntity(), according to the api it does what you need.Thaxton
yes, ContainerResponseContext.getEntity() but same method or behavior i need in ContainerRequestContext Is there any way to get Entity object from ContainerRequestContextFango
There is no way to obtain the object using this type of filter, because it is binded to the outer level of the request/response cycle. What you need may be obtained implementing a ReaderInterceptor, and using the method proceed() of the ReaderInterceptorContext, passed to aroundReadFromThaxton
let us continue this discussion in chatThaxton

© 2022 - 2024 — McMap. All rights reserved.