Getting Response in ContainerResponseFilter's

2019-02-13 22:12发布

问题:

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.

回答1:

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

}