小编Leo*_*Leo的帖子

使用JAX-RS/RESTEasy实现CORS的Ajax请求

我有两个服务器(Apache和JBoss AS7),我需要提供对客户端的所有http方法的访问.所有这些请求必须通过ajax发送.客户端代码示例:

$.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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

在JBoss AS7中我使用RESTEasy,实现如下CORS:

@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) …
Run Code Online (Sandbox Code Playgroud)

ajax json jax-rs resteasy cors

5
推荐指数
2
解决办法
2万
查看次数

标签 统计

ajax ×1

cors ×1

jax-rs ×1

json ×1

resteasy ×1