Javaweb网cors跨域ajax数据交互

时间:2022-05-28 12:33:05


1、通过Maven引用

cors-filter、java-property-utils二个jar包,修改pom.xml文件,加入下面内容

<!-- 跨域问题 -->
<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>


2、在web.xml里面配置过滤器,使用引入的jar中定义好的过滤器。注意修改cors.allowOrigin节点,如果允许所有站点跨域访问,可以修改为[*],如果是多个站点,可以用[,]分隔配置。


<!-- 跨域问题 -->
<filter>
<description>跨域过滤器</description>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>http://127.0.0.1:8380</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、通过Jquery跨域调用数据,实例代码如下:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>跨域测试</title>

<style type="text/css">
body{
margin:0px auto 0px auto;
}
.div_container {
margin: 0px auto 0px auto;
width: 100%;
height: 200px;
}
.div_container > iframe {
width: 100%;
height: 100%;
}
</style>
</head>
<body>


<div>
</div>
<button id="btn_test">跨域调用</button>
<div id="div_show"></div>
<script src="jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(function () {


$('#btn_test').click(function () {
//alert('dddd');
//var iframe_main = $("#iframe_main").contents();
//iframe_main.find("#account").val('test');
$.ajax({
url: "http://10.18.25.119:8480/jxfp/index.jsp",
type: "GET",
dataType: "text",
timeout: 10000,
xhr: function () { //这是关键 获取原生的xhr对象 做以前做的所有事情
var xhr = jQuery.ajaxSettings.xhr();
xhr.withCredentials = true;
return xhr;
},
success: function (data) {
$("#div_show").html(data);
//Console.log(data);
},
error: function (e) {
$("#div_show").html(e.statusText);
}
});
});
});
</script>
</body>
</html>