泽西岛,宁静的网络服务,跨域访问拒绝

时间:2016-03-14 07:50:52

标签: java web-services rest jersey

我使用netbeans创建了宁静的Web服务,并得到了“跨域访问拒绝”的错误

我添加了“跨源资源过滤器”

以下是我的代码。

@Provider
public class CrossOriginResourceSharingFilter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) {
    response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
    response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE");
    response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type");
}

}

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {

@Override
public Set<Class<?>> getClasses() {
    Set<Class<?>> resources = new java.util.HashSet<>();
    addRestResourceClasses(resources);
    return resources;
}

private void addRestResourceClasses(Set<Class<?>> resources) {
    resources.add(WebService.CategoryFacadeREST.class);
    resources.add(WebService.CrossOriginResourceSharingFilter.class);
    resources.add(WebService.ProductFacadeREST.class);
    resources.add(WebService.ReviewFacadeREST.class);
}   
}

1 个答案:

答案 0 :(得分:0)

我认为问题是,Content-Type中只允许Access-Control-Allow-Headers标头。请在请求中查找标题Access-Control-Request-Headers ...在Access-Control-Allow-Headers标题中设置内容或尝试此代码:

String reqHead = requestContext.getHeaderString("Access-Control-Request-Headers");
if (null != reqHead && !reqHead.equals("")) {
    responseHeaders.putSingle("Access-Control-Allow-Headers", reqHead);
}

通常:出于安全原因,您不应在生产环境中使用通配符和此类代码。