ContainerResponseFilter 不起作用 [英] ContainerResponseFilter not working

查看:52
本文介绍了ContainerResponseFilter 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在带有 REST 服务的 Wildfly 8.1 中,我想实现 CORS ContainerRequestFilter 和 ContainerResponseFilter.

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

我的请求过滤器工作正常,但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");
    }

}

在我看来,这是一个 Wildfly/resteasy 错误.你有其他想法/我错过了什么吗?

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

推荐答案

您在问题中混合了 ContainerRequestFilterContainerResponseFilter.当您想向客户端发送额外的标头时,ContainerResponseFilter 是正确的.

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.

@PreMatching 注释可以应用于 ContainerRequestFilter 以指示在实际资源匹配发生之前,应在应用程序中的所有资源上全局应用此类过滤器".

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".

将其添加到 ContainerResponseFilter 没有意义.只需删除注释,您的过滤器就会起作用.

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

这篇关于ContainerResponseFilter 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆