“Access-Control-Allow-Origin:*”对REST Web服务没有影响

时间:2011-03-23 13:57:25

标签: rest jquery cross-domain jersey

我从JavaScript客户端(在机器A上运行)到Web服务器(在机器B上运行)进行AJAX调用。 客户端尝试访问RESTful Web服务(Jersey)公开的URL,并且阻止了错误:

  

原点http://localhost/不是   允许的   访问控制允许来源

在服务器中,我添加了2个标头参数,允许访问任何客户端。但它没有帮助:

@Context
private HttpServletResponse servlerResponse;

@POST
@Path("testme")
public void test(){
    servlerResponse.addHeader("Access-Control-Allow-Origin", "*");
    servlerResponse.addHeader("Access-Control-Allow-Credentials", "true");
}

相同的头文件适用于JSP:

<%
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Credentials", "true");
%>
<html>
<head><title>test jsp</title></head>
<body>
test
</body>
</html>

我错过了什么吗?

感谢

P.S客户端部分是:

$.ajax({
    type: "POST",
    url: "http://localhost:8080/login/testme",
    dataType: 'json',
    success: onLoginSuccess,
    error: onLoginError
});

2 个答案:

答案 0 :(得分:6)

作为解决方案,我们实现了javax.servlet.Filter,它为每个响应添加了必需的标头:

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, java.io.IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    // This should be added in response to both the preflight and the actual request
    response.addHeader("Access-Control-Allow-Origin", "*");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.addHeader("Access-Control-Allow-Credentials", "true");
    }

    chain.doFilter(req, resp);
}

答案 1 :(得分:3)

@epeleg这是我喜欢这样做的首选方式是对响应进行过滤(Jersey 2.x):

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext,
            ContainerResponseContext responseContext) throws IOException {

        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    }
}