我想知道如何设置跨域策略,是使用过滤器还是使用web.xml?怎么加呢?我用jetty和jersey。
这是我的主
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
context.setResourceBase(".");
server.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "my.package.rest");
server.start();
server.join();
}
我的web . xml <web-app>
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
实际上我只是找到了答案看这个我发现,我们只需要添加服务器"响应"的头属性,这样:
@GET
@Path("sin")
@Produces(MediaType.TEXT_PLAIN)
public Response hello() {
String var = "[0.0, 0.0]";
return Response.ok().entity(var)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();
}
我认为这种方式也适用于JSON或其他。
希望对你有帮助。
思路相同,方法不同。使用以下代码创建一个ContainerResponseFilter,一次性为所有jax-rs web服务放置报头:
@Provider
public class HeadersReponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
}
}
和以下配置在你的web.xml:
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>your.webservices.package</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>your.webservices.package.HeadersReponseFilter</param-value>
</init-param>
<async-supported>true</async-supported>
</servlet>
欢呼。:)