ContainerResponseFilter not working

穿精又带淫゛_ 提交于 2019-11-28 03:38:01

问题


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.



来源:https://stackoverflow.com/questions/25591140/containerresponsefilter-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!