Java RESTful服务的Jquery调用不工作CORS

Posted

技术标签:

【中文标题】Java RESTful服务的Jquery调用不工作CORS【英文标题】:Jquery call of Java RESTful service not working CORS 【发布时间】:2014-02-06 08:46:45 【问题描述】:

我在 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;

我无法解决它。请提出建议。

这是我的 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>

【问题讨论】:

【参考方案1】:

以下内容可以添加到响应中,它可以防止 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)

    
);

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

【讨论】:

【参考方案2】:

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

Link 1

Link 2

感谢大家的大力帮助。

【讨论】:

你太棒了兄弟@Kumar

以上是关于Java RESTful服务的Jquery调用不工作CORS的主要内容,如果未能解决你的问题,请参考以下文章

使用带有摘要身份验证、jquery ajax 调用的 RestFul PHP Web 服务

带有 RESTful JSON 服务、HTML5 和 jQuery ajax 的 Java Web 框架

没有收到从 jQuery ajax 到 JAVA RESTful webservice 的任何请求

如何在Java客户端调用RESTful服务

java客户端调用restful接口

在java中为一次调用执行两次Restful Web服务