我正在尝试将CORS-Filter添加到Jersey 1.8 WebService。
@ApplicationPath("/")
public class RESTConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> set = new HashSet<>();
set.add(CORSFilter.class);
set.add(super.getClass());
return super.getClasses(); //To change body of generated methods, choose Tools | Templates.
}
}
这是我在这里的CORSFilter():
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHttpHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
return response;
}
}
我仍然从我的Javascript-WebApp获得CORS错误。 查看网络流量,未发送任何CORS标头。我在这里缺少什么?
答案 0 :(得分:0)
您的RESTConfig
不正确
@ApplicationPath("/")
public class RESTConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> set = new HashSet<>();
set.add(CORSFilter.class);
// wrong
//set.add(super.getClass());
//return super.getClasses();
// corrected
set.addAll(super.getClasses());
return set;
}
}
另外如果你覆盖getClasses()
方法,你不仅要添加过滤器,还要添加所有REST资源
set.add(MyHelloWorldResource.class);
set.add(AnotherResource.class);
作为替代方案,您可以扩展Jerseys ResourceConfig
类,在这种情况下,您可以指定要扫描资源和过滤器的整个包。
public class RESTConfig extends ResourceConfig {
public RESTConfig() {
// scan the whole package and register all appropriate classes
packages("org.foo.rest;org.bar.rest");
// register single class
register(CORSFilter.class);
}
}
有关更多信息,请参阅Jersey documentation
答案 1 :(得分:0)
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>