RESTful webservice:如何在java中设置头以接受Access-Control-Allow-Origin允许的XMLHttpRequest

我有一个RESTful webservice,它将返回字符串,它是用 Java(JAX-WS)编写的.
我的问题是当我发送请求给该webservice的URL,如下所示:

HTTP://本地主机:8080 /项目/ Web服务/的GetList / getListCustomers

在控制台中,给我以下错误消息:

XMLHttpRequest cannot load url Origin localhost is not allowed
by Access-Control-Allow-Origin

我该怎么处理这个问题?

Java代码:

@GET
@Path("/getsample")
public Response getMsg() { 
    String output = "Jersey say : " ;   
    return Response.status(200).entity(output).build();
}
阅读这里关于你的问题CORS: http://enable-cors.org/

检查这个是否在你的getMsg()方法中帮助你:return Response.ok(output).header(“Access-Control-Allow-Origin”,“*”).

如果以上不行,请尝试为您的服务添加泽西过滤器.创建过滤器类:

package your.package;

public class CORSFilter implements ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest creq, ContainerResponse cresp) {

        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

        return cresp;
    }
}

并在以后注册win web.xml:

<servlet>
<servlet-name>CORS Filter</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>your.package.CORSFilter</param-value>
 </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>CORS Filter</servlet-name>
    <url-pattern>/webservices/*</url-pattern>
</servlet-mapping>

另一个解决方案是在资源中使用此代码为浏览器提供OPTIONS.把它放在你拥有@GET的课堂里.

@OPTIONS
  @Path("/getsample")
  public Response getOptions() {
    return Response.ok()
      .header("Access-Control-Allow-Origin", "*")
      .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
      .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
  }

如果不这样做,请尝试将“Access-Control-Allow-Origin”头文件的“*”与您访问此资源的自定义域进行交换.胃内如果你从http:// localhost :: 8080这样调用它,使用这样的东西(“Access-Control-Allow-Origin”,“http:// localhost:8080”),而不是星号“*”.

相关文章
相关标签/搜索