我在Eclipse中有一个Java应用程序。使用Jersey,它在本地成功创建了一个网页(localhost)。
问题是我在另一台尝试访问该网页的服务器上有一个javascript,它会引发CORS错误。
Jersey / WADL应用程序是否有内置的CORS支持?
我已经尝试创建支持CORS的Jersey过滤器 - 遵循这些instructions。没运气。 :(我正在调查this,但我不确定它是否是我想做的正确选择。
基本上,我的标题目前是:
但我希望它看起来像这样:
全部谢谢!
修改
根据jgm的建议,我创建了一个过滤器(称为CORSFilter)并添加了请求依赖项。我是否在web.xml文件中正确注册了过滤器?
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>createJPA</display-name>
<servlet>
<servlet-name>Jersey Root REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Root REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>model.producer.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
答案 0 :(得分:1)
这是一个简单的针对运动衫的CORS过滤器,改编自Weald Technology utilities:
import com.google.inject.Inject;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.wealdtech.jersey.CORSConfiguration;
/**
* Filter to handle cross-origin resource sharing.
*/
public class CORSFilter implements ContainerResponseFilter
{
private static final String ACAOHEADER = "Access-Control-Allow-Origin";
private static final String ACRHHEADER = "Access-Control-Request-Headers";
private static final String ACAHHEADER = "Access-Control-Allow-Headers";
private static final String ACAMHEADER = "Access-Control-Allow-Methods";
private static final String ACACHEADER = "Access-Control-Allow-Credentials";
private final transient CORSConfiguration configuration;
@Inject
public CORSFilter(final CORSConfiguration configuration)
{
this.configuration = configuration;
}
@Override
public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response)
{
response.getHttpHeaders().add(ACAOHEADER, this.configuration.getOrigin());
final String requestHeaders = request.getHeaderValue(ACRHHEADER);
response.getHttpHeaders().add(ACAHHEADER, requestHeaders);
response.getHttpHeaders().add(ACAMHEADER, this.configuration.getAllowedMethods());
response.getHttpHeaders().add(ACACHEADER, this.configuration.allowCredentials());
return response;
}
}
对于配置,您可以use the existing configuration setup或将其合并到您自己的系统中。请注意,这使用Google Guice来注入配置,如果您不使用Guice,则需要手动执行此操作。