Ajax请求与JAX-RS / RestEasy的实施CORS [英] Ajax request with JAX-RS/RESTEasy implementing CORS
问题描述
我有两台服务器(Apache和JBoss的AS7),我需要提供访问所有的HTTP方法给客户端。所有这些请求都必须通过AJAX发送。 客户端code例:
I have two servers (Apache and JBoss AS7) and I need to provide access to all http methods to a client. All these request must be sent via ajax. Example of the client code:
$.ajax({
type: "get",
url: "http://localhost:9080/myproject/services/mobile/list",
crossDomain: true,
cache: false,
dataType: "json",
success: function(response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(jqXHR.responseText);
console.log(errorThrown);
}
});
在JBoss的AS7我使用RestEasy的,实现CORS如下:
In JBoss AS7 I'm using RESTEasy, implementing CORS as follows:
@Path("/mobile")
@Provider
@ServerInterceptor
public class GroupMobile implements MessageBodyWriterInterceptor {
@Inject
private GroupDAO groupDAO;
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public List<Group> getGroups() {
return groupDAO.listAll();
}
@Override
public void write(MessageBodyWriterContext context) throws IOException,
WebApplicationException {
context.getHeaders().add("Access-Control-Allow-Origin", "*");
context.proceed();
}
@OPTIONS
@Path("/{path:.*}")
public Response handleCORSRequest(
@HeaderParam("Access-Control-Request-Method") final String requestMethod,
@HeaderParam("Access-Control-Request-Headers") final String requestHeaders) {
final ResponseBuilder retValue = Response.ok();
if (requestHeaders != null)
retValue.header("Access-Control-Allow-Headers", requestHeaders);
if (requestMethod != null)
retValue.header("Access-Control-Allow-Methods", requestMethod);
retValue.header("Access-Control-Allow-Origin", "*");
return retValue.build();
}
}
web.xml和beans.xml文件是空文件。 当我访问MYIP:8080(阿帕奇),我得到错误信息:
web.xml and beans.xml are empty files. When I access MyIP:8080 (Apache), I get the error message:
XMLHttpRequest cannot load http://localhost:9080/myproject/services/mobile/list?_=1359480354190. Origin http://MyIP:8080 is not allowed by Access-Control-Allow-Origin.
有谁知道什么是错?
Does anybody know what is wrong?
推荐答案
您遇到的问题是你正在尝试做跨站点脚本。您访问的页面的http:// MYIP:8080
等的浏览器访问该域的外部资源preventing你。这是非常特定浏览器和基于浏览器的变通都将是不同的(你可以在浏览器关闭全局的安全,并在每个站点的基础在IE浏览器)。
The problem you are having is your are trying to do cross-site scripting. You accessed the page at http://MyIP:8080
and so the browser is preventing you from accessing resources outside that domain. This is very browser specific and browser based work arounds will all be different (you can disable security in Chrome globally, and on a per site basis in IE).
如果您加载页面的http://本地主机:8080
,它应该然后允许你访问查询。或者,你可以实现一个代理,它会转发请求。
If you load the page as http://localhost:8080
, it should then allow you access the query. Alternatively, you can implement a proxy which will forward the request.
这篇关于Ajax请求与JAX-RS / RestEasy的实施CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!