标签:技术 modified 协议 XML js代码 app use domain 跨域
一、概念
1. 如果两个页面的协议、域名和端口是完全相同的,那么它们就是同源的,不同则为跨域
2. ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器出于安全考虑,不允许js代码进行跨域操作。
二、
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 nativeXHR
object. For example, you can use it to setwithCredentials
totrue
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); } });
标签:技术 modified 协议 XML js代码 app use domain 跨域
原文地址:http://www.cnblogs.com/an5211/p/7149326.html