天天看点

ajax之POST跨域请求

1,简短说明

ajax跨域请求,常见的有jsonp,httpClient,CORS插件等

这次主要介绍CORS插件的使用

几个问题

1,什么是跨域:浏览器同源策略,协议、域名和端口,三者有一个不同,则跨域

2,什么是jsonp及如何使用【这里不做重点介绍】

3,什么是httpClient及如何使用【这里不重点介绍】

4,什么是CORS及如何使用【重点介绍】

2,CORS插件配置

CORS(Cross-Origin Resource Sharing,跨源资源共享)是W3C出的一个标准

其思想是使用自定义的HTTP头部让浏览器与服务器进行沟通

从而决定请求或响应是成功还是失败

环境:JDK1.7,mvn-v3.3.9

下载CORS插件:cors-filter-2.6.jar和java-property-utils-1.13.jar

将两个jar包打到maven仓库中【maven本地打jar包,这里不做重点介绍】

打包文件夹位置可参考jar包下载页面中给出的默认地址

xml配置

pom.xml:

<!--https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter -->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils -->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>java-property-utils</artifactId>
    <version>1.13</version>
</dependency>

           

web.xml:

<!-- CORS跨域请求 -->
<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>

           

3,参考链接

https://www.cnblogs.com/shirly77/p/6440635.html?utm_source=itdadao&utm_medium=referral

https://www.cnblogs.com/yanglang/p/6720887.html

http://www.ruanyifeng.com/blog/2016/04/cors.html

https://blog.csdn.net/wxb880114/article/details/80606434

http://www.uxuew.cn/vuejs/7135.html

http://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/1.7

继续阅读