Getting Response in ContainerResponseFilter's

2019-02-13 21:26发布

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条回答
smile是对你的礼貌
2楼-- · 2019-02-13 22:28

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

}
查看更多
登录 后发表回答