ContainerResponseFilter not working

2019-01-26 12:41发布

问题:

In wildfly 8.1 with REST services, I wanted to implement CORS ContainerRequestFilter and ContainerResponseFilter.

My request filter is working properly but ContainerResponseFilter never gets loaded nor called

package org.test.rest;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;

@Provider 
@PreMatching // <-- EDIT : This was my mistake ! DO NOT ADD THIS
public class CorsResponseFilter implements ContainerResponseFilter {
    public CorsResponseFilter() {
        System.out.println("CorsResponseFilter.init");
    }

    @Override
    public void filter(ContainerRequestContext req,
            ContainerResponseContext resp) throws IOException {
        System.out.println("CorsResponseFilter.filter");
        resp.getHeaders().add("Access-Control-Allow-Origin", "*");
        resp.getHeaders().add("Access-Control-Allow-Credentials", "true");
        resp.getHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, DELETE, PUT");
        resp.getHeaders().add("Access-Control-Allow-Headers",
                "Content-Type, Accept");
    }

}

This seems to me as a Wildfly / resteasy bug. Do you have another idea / am I missing something ?

回答1:

You are mixing ContainerRequestFilter and ContainerResponseFilter in your question. As you want to send additional Headers to the client the ContainerResponseFilter is the right one.

The @PreMatching annotation can be applied to a ContainerRequestFilter "to indicate that such filter should be applied globally on all resources in the application before the actual resource matching occurs".

Adding it to a ContainerResponseFilter does not make sense. Just remove the annotation and your filter should work.