cors,跨域资源共享,Java配置

时间:2023-08-14 18:05:20

一、概念

1. 如果两个页面的协议、域名和端口是完全相同的,那么它们就是同源的,不同则为跨域

2. ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器出于安全考虑,不允许js代码进行跨域操作。

3. 例子:

http://www.abc.com/index.html 调用 http://www.abc.com/server.do (非跨域)

http://www.abc.com/index.html 调用 http://www.def.com/server.php (主域名不同:abc/def,跨域)

http://abc.abc.com/index.html 调用 http://def.abc.com/server.php (子域名不同:abc/def,跨域)

http://www.abc.com:8080/index.html 调用 http://www.abc.com:8081/server.do (端口不同:8080/8081,跨域)

http://www.abc.com/index.html 调用 https://www.abc.com/server.do (协议不同:http/https,跨域)

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面,就不会被执行。

二、

1. 文档:http://software.dzhuvinov.com/cors-filter.html

2.  cors--->  Cross-Origin Resource Sharing  --->跨域资源共享

3. 添加依赖

<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.10</version>
</dependency>

4. web.xml 添加如下代码:

<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

5. 添加上面的过滤器,其实就是在返回的response中,添加如下header

        response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

6. jquery请求也可以是AngularJS

$.ajax("url", {
type: "POST",
//A map of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.
//XHR:XMLHttpRequest (XHR) ,基于XML技术的Http请求。设置本地XHR对象的“名-值”映射。例如,可以在需要时设置“withCredentials”为真而执行跨域名请求。
//withCredentials: https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials
   xhrFields: {
withCredentials: true,
useDefaultXhrHeader: false
},
data: {
type: "test"
},
dataType: 'json',
crossDomain: true,
success: function(data, status, xhr) {
console.log(data);
}
});