如何使用JAX RS API 1.1启用CORS

时间:2016-11-02 12:51:46

标签: cors resteasy jboss6.x

我使用JBoss 6.4 EAP和Resteasy 2.3.10 Final和jaxrs api spec 1.1(所有这些库都已在容器中提供)。

我想念ContainerResponseFilter,因为它包含在jaxrs 2.0规范中,因此SO question在我的情况下不起作用。 我可以使用哪种方法来启用CORS?

1 个答案:

答案 0 :(得分:3)

我必须以这种方式实现标准的javax.servlet.Filter:

package javax.servlet;

import java.io.IOException;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns="/*")
public class ApiOriginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");

        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }

}