CORS:Cross-Origin Resource Sharing(跨域资源共享)

CORS被浏览器支持的版本情况如下:Chrome 3+、IE 8+、Firefox 3.5+、Opera 12+、Safari 4+

问题描述:A域中的脚本请求B域中的资源出现这种问题

报错信息:

XMLHttpRequest cannot load http://localhost:8082/servletdemo/doTest. No 'Access-Control-Allow-Origin' header is present on the requested resource.

Origin 'http://localhost:8080' is therefore not allowed access.

问题分析:

两个不同的域之间发送请求,浏览器出于安全因素考虑,所以不允许这种访问。

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content,

please consider using CORS to open it up for universal JavaScript/browser access.

Granting JavaScript clients basic access to your resources simply requires adding one HTTP Response Header, namely:

Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://example.com:8080/

问题解决:

以下提供几种解决方法,根据实际情况选择

一、容器层面,影响范围是容器下的所有webapp应用

in tomcat/conf/web.xml ex:

<filter>
      <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

ps:这个过滤器只针对apache-tomcat-7.0.41及以上版本。

二、单个应用,只作用于这个项目本身

in webapp/WEB-INF/web.xml
<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

三、一组资源层面,作用于指定Filter过滤的全部请求资源

Filter方法代码 ex:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  res.addHeader("Access-Control-Allow-Origin", "*");
  res.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires,   Content-Type, X-E4M-With");
  chain.doFilter(req, res);
}

四、单个资源层面,只针对某一个资源

Servlet方法代码 ex:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setHeader("Access-Control-Allow-Origin","*");
  PrintWriter out = response.getWriter();
  out.write("{/"key/":/"value/"}");
  out.flush();
  out.close();
}

其中spring framework在4.2及以上支持cors注解,可参考https://spring.io/blog/2015/06/08/cors-support-in-spring-framework;

另一种https://spring.io/guides/gs/rest-service-cors/

五、针对单兵开发,我们原型maven-Archetype-wepapp提供两种支持

tomcat7-maven-plugin
<plugin>
  <groupId>org.apache.tomcat.maven</groupId>
  <artifactId>tomcat7-maven-plugin</artifactId>
  <version>2.2</version>
  <configuration>
    <path>/servletdemo</path>
    <port>8082</port>
    <server>tomcat</server>
    <url>http://localhost:8080/manager/text</url>
  <!-- Enable CORS -->
  <tomcatWebXml>src/test/resources/tomcat.web.xml</tomcatWebXml>
  </configuration>
</plugin>

jetty-maven-plugin
<plugin>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-maven-plugin</artifactId>
  <version>9.3.2.v20150730</version>
  <configuration>
    <scanIntervalSeconds>10</scanIntervalSeconds>
  <webApp>
    <contextPath>/servletdemo</contextPath>
    <!--Fix file locking problem with jettyrun Enable CORS-->
    <defaultsDescriptor>src/test/resources/jetty.web.xml</defaultsDescriptor>
  </webApp>
  <httpConnector>
    <!-- mvn -Djetty.port=8082 jetty:run -->
    <port>8082</port>
  </httpConnector>
  </configuration>
<dependencies>
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-servlets</artifactId>
  <version>9.3.2.v20150730</version>
  </dependency>
</dependencies>
</plugin>

跨域资源共享(CORS)问题解决方案的更多相关文章

  1. 跨域资源共享CORS与JSONP

    同源策略限制: 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果没有同源策略,攻击者可以通过JavaScript获取你的邮件以及其他敏感信息,比如说 ...

  2. 跨域解决方案 - 跨域资源共享cors

    目录 1. cors 介绍 2. 原理 3. cors 解决跨域 4. 自定义HTTP 头部字段解决跨域 5. 代码演示 5. 参考链接 1. cors 介绍 cors 说的是一个机制,其实相当于一个 ...

  3. VUE SpringCloud 跨域资源共享 CORS 详解

    VUE  SpringCloud 跨域资源共享 CORS 详解 作者:  张艳涛 日期: 2020年7月28日 本篇文章主要参考:阮一峰的网络日志 » 首页 » 档案 --跨域资源共享 CORS 详解 ...

  4. 网络编程-跨域资源共享 CORS

    目录 1.什么是同源策略? 2.跨域资源共享 CORS 3.预检请求 4.CORS相关字段 5.Golang实现跨域 6.参考资料 1.什么是同源策略? 如果两个 URL 的 protocol.por ...

  5. 跨域资源共享 CORS

    CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing). 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从 ...

  6. 跨域资源共享 CORS 详解

    CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing). 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从 ...

  7. 使Web Api 支持跨域资源共享(CORS)

    Reference:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api Imp ...

  8. 跨域资源共享CORS详解

    简介 CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing). 它允许浏览器向跨源服务器,发出XMLHttpRequest请 ...

  9. 跨域资源共享 CORS 详解(转)

    add by zhj: 公司在一个web产品上,做前后端分离,前后端提供独立的服务,使用不同的域名,通过http进行交互,在 前端,会涉及到跨域访问的问题,前端使用了CORS,后端同时需要做相应修改, ...

随机推荐

  1. [Linux]cmd to use

    0x01 Linux Perfermance Analysis in 60s 1> uptime ---load averages 2> dmesg -r | tail ---kernel ...

  2. VS.Net 2015 Update3 学习(2) jquery-form, jquery-validation,jquery-validation-unobtrusive一起用

    我觉DataAnnotations非常酷的一个功能.但是教程中的@ajaxform的却不怎么优雅,需要全局的onSucces等函数.因此我使用jquery-form做ajax提交. function ...

  3. Pod 的安装

    1.如果之前已经安装过的 gem list --local | grep cocoapods 会看到如下输出: cocoapods (1.1.1)cocoapods-deintegrate (1.0. ...

  4. go排序

    补注: 近来又看 go 的排序, 发现以前对 go 的排序理解的有点浅了. go 的排序思路和 c 和 c++ 有些差别. c 默认是对数组进行排序, c++ 是对一个序列进行排序, go 则更宽泛一 ...

  5. viewPager + fragment

    有两种实现方式,一种是 fragmentActivity + FragmentPagerAdapter (Fragment,FragmentManager需要导包:android.support.v4 ...

  6. mybatis-缓存1

    以下转自:http://www.cnblogs.com/weidiao/p/5469046.html mybatis有两级缓存机制,一级缓存默认开启,可以在手动关闭:二级缓存默认关闭,可以手动开启.一 ...

  7. R语言实战(二)数据管理

    本文对应<R语言实战>第4章:基本数据管理:第5章:高级数据管理 创建新变量 #建议采用transform()函数 mydata <- transform(mydata, sumx ...

  8. reqwest请求api和约束(转载)

    转自:https://www.oschina.net/p/reqwest reqwest 用于浏览器异步HTTP请求.支持xmlHttpRequest, JSONP, CORS, 和 CommonJS ...

  9. 20155229-付钰涵-分析自我技能延展到c语言学习状况

    我的小技能 我记得幼儿园时表演的舞蹈,也记得从水彩到素描的学习,还记得小学和初中获得的钢琴省级奖项. 舞蹈止于一年级,绘画止于三年级,钢琴从学前班到高一那十年的时间里有过断续. 03年-04年的那个冬 ...

  10. JavaWeb前端:CSS

    CSS 主要是要熟悉的掌握选择器 Div 的盒模型: 整个网页被切割成一个一个盒子,盒子可以套盒子,每个盒子通过以下几个主要属性来控制显示位置: 边框 Border-top, Border-botto ...