关于跨域问题处理!

在新公司,遇到跨域问题,开始装了两个谷歌跨域插件 Allow-Control-Allow-Origin: *和CORS Toggle,发现没有用还是报跨域的错误。然后在项目中做跨域的处理。

以MAVEN项目为例

  前端请求(不知道前端请求加不加headers块有没有影响)

  $.ajax({
        type : type,
        dataType : "json",
        url : url,
        data : parm,
        cache : false,
        success : function(data) {
            if (data.meta.code == 'S002') {
                callBack(data);
            } else {
                console.log(data.meta.code + "  " + data.meta.message);
                alertplan(data.meta.message);
            }
        },
        headers : {
            "Access-Control-Allow-Origin" : "http://10.252.1.167",
            "Access-Control-Allow-Headers" : "X-Requested-With",
            'X-TOKEN' : loadToken()
        },
        error : function(XHR, textStatus, errorThrown) {
            alertplan("XHR=" + XHR + "\ntextStatus=" + textStatus
                    + "\nerrorThrown=" + errorThrown);
        },
        complete:function(XMLHttpRequest,status){
            $(".lordinlayer").hide();
        }
    });

 

  在pom.xml中加上需要的依赖

   <dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>cors-filter</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest_2.10</artifactId>
            <version>2.0</version>
            <scope>test</scope>
        </dependency>

 

  然后在web.xml中加上一个过滤器

  <filter>
          <filter-name>CORS</filter-name>
          <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>CORS</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>

需要的jar包是 cors-filter-2.4.jar

最终测试,通过!

 

posted @ 2017-03-16 09:41  路途寻码人  阅读(298)  评论(0编辑  收藏  举报