Jquery调用Java RESTful服务不能正常工作CORS

时间:2014-01-17 05:52:54

标签: java rest jquery jax-rs cors

我在Tomcat 7上部署了一个休息服务并正在运行。我可以通过浏览器获取响应数据,但是当我通过jQuery尝试它时,它显示错误。请检查快照。

@Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) req;
        HttpServletResponse httpRes = (HttpServletResponse) res;

        //System.out.println("Client Ip is : "+ SecurityFilter.getClientIpAddr(httpReq));

        String domain = new URL(httpReq.getRequestURL().toString()).getHost();
        //System.out.println("Domain is " + domain);

        // referrer
        String referrer = httpReq.getHeader("referer");
        //System.out.println("Referral URL is -" + referrer);

        // Security Key
        String securityKey = httpReq.getParameter("secKey");
        //System.out.println("Security Key Parameter " + securityKey);

        // Origin
        // No Origin header present means this is not a cross-domain request
        String clientOrigin = httpReq.getHeader("Origin");
        //System.out.println("Origin of the Request " + clientOrigin);

        // CORS implementation
        httpRes.addHeader("Access-Control-Allow-Origin", "*");
        httpRes.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        // httpRes.addHeader("Access-Control-Allow-Origin", clientOrigin);

        if ("OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
            httpRes.addHeader("Access-Control-Allow-Credentials", "true");
        }

        ValidateClient vl = new ValidateClient();

        String secKey = "fmg_seckey"; //"SEC_1";;
        String clientUrl = "fmggroup.com";//"www.xyzclient1.com";

        // if request is coming from third party. Referral will be null if all
        // request is from same server.

        if  (referrer != null) {
            clientUrl = referrer.split("/")[2];
            secKey = securityKey;
        }

        //System.out.println("Security Key " + secKey);
        //System.out.println("Domain Name for the client " + clientUrl);


        if (vl.isValidClient(secKey, clientUrl)) {
            // httpReq.getRequestDispatcher("/intellixservices/activetime").forward(httpReq,httpRes);
            chain.doFilter(httpReq, httpRes);
        } else {

            httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Not Authorised");
            // httpReq.getRequestDispatcher("/intellixservices/exception").forward(httpReq,
            // httpRes);

        }

    }

在资源类中:

// CORS implementation
private String corsHeaders;

private Response makeCORS(ResponseBuilder responseBuilder, String returnMethod) {
    ResponseBuilder rb = responseBuilder.header("Access-Control-Allow-Origin", "*")
       .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

    if (!"".equals(returnMethod)) {
       rb.header("Access-Control-Allow-Headers", returnMethod);
    }
    return rb.build();
 }

 private Response makeCORS(ResponseBuilder responseBuilder) {
    return makeCORS(responseBuilder, corsHeaders);
 }

 @OPTIONS
 public Response getEmployee(@HeaderParam("Access-Control-Request-Headers") String request) {
     corsHeaders = request;
     return makeCORS(Response.ok(), request);
 }

然后返回

Response response = Response.status(404).build();

if (mf != null) {
             response = makeCORS(Response.status(200).entity(mf));
         } else {
             response = makeCORS(Response.status(500));
         }

         return response;

我无法解决它。请建议。

enter image description here

这是我的jQuery调用: -

<html>
   <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <script type="application/javascript">      
         (function($) {
            var url = 'http://localhost:8888/IntellixWebApi/intellixservices/dnareport/MTk3MC0wOS0wNFQwNjowNTowMA==/NDEuNTU4MTUyNSA=/LTczLjA1MTQ5NjYg/QW1lcmljYS9OZXdfWW9yaw==/MTpBOjB8QToxOjF8MToxOjE=/json';

            $.ajax({
               type: 'GET',
               url: url,
               async: true,
               contentType: 'application/json',
               success: function(response) {
                  alert("success");
               },
               error: function(xhr) {
                  alert('Error!  Status = ' + xhr.status + " Message = " + xhr.statusText);
               }
            });
         })(jQuery);
      </script>
   </head>
   <body>
      <!-- we will add our HTML content here -->
   </body>
</html>

2 个答案:

答案 0 :(得分:3)

任何方式我都经过大量的谷歌搜索解决了这个问题。我在web.xml中添加了CORS过滤器和java实用程序jar过滤器以及一些配置更改。这些链接非常有用

Link 1

Link 2

谢谢大家的帮助。

答案 1 :(得分:0)

可以将以下内容添加到响应中,它可以防止CORS问题:

Response.status(200)
            .header("Access-Control-Allow-Origin", request.getHeader("Origin"))
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Credentials", "true")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "1209600")
            .entity(applicationSyncService.buildApplicationData())
            .build();

响应的类型为:HttpServletRequest。但这可能是一个安全漏洞。

你可以像这样从jquery拨打电话:

$.ajax({

    xhrFields: {
    withCredentials: true
},
    type: 'GET',
    url: server + '/hello',
    dataType: 'json',
    async: true,
    success: function(data){

        if(data.connected){
            //your code
    },
    error: function(a, b, c){

    }
});

这是一个更简单的解决方案,无需使用过滤器。