首先下载jar包
cors-filter与java-property-utils
<!-- https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter -->
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils -->
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.10</version>
</dependency>
修改web.xml
增加以下代码(最好放在其他filter前边)
<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>
GET格式
function testGet(){
$.ajax({
type: "GET",
contentType: "application/json;charset=utf-8",
url: ": "url",
",
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function (response) {
console.log(res(response)// 返回的 json 数据
}
});
}
POST格式
var data={
" name":"",
};
function testPost(){
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: ": 请求地址URL,
",
crossDomain: true,
dataType: 'json',
data:ta:JSON.stringify(dat(data),
xhrFields: {
withCredentials: true
},
success: function (response) {
console.log(res(response)// 返回的 json 数据
}
});
}