在处理跨域AJAX请求有许多方法。我这里用的是 CORS,
CORSFilter
CORSFilter是Apache官方提供一个支持CORS跨域的过滤器:
详细说明: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html
在maven配置文件中导入依赖
<!--CORS--> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.6</version> </dependency>
在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>http://127.0.0.1:8020</param-value> </init-param> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>POST,GET,OPTIONS,DELETE,PUT</param-value> </init-param> <init-param> <param-name>cors.supportedHeaders</param-name> <param-value>Content-Type,Accept,Origin,XRequestedWith,ContentType,LastModified</param-value> </init-param> <init-param> <param-name>cors.exposedHeaders</param-name> <param-value>SetCookie</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>
客户端
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>跨域AJAX请求</title> </head> <body> <h2>跨域AJAX请求</h2> <button type="button" id="btnAjax">ajax请求</button> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $("#btnAjax").click(function() { $.get("http://localhost:8080/mvc02/users", "", function(data) { console.log(JSON.stringify(data)); }, "json"); }); </script> </body> </html>
服务器(本人用的是Spring MVC):
@RestController @RequestMapping(path="/users") public class UsersController { @Resource EmpService empService; /*查询所有*/ @RequestMapping(path = "",method = RequestMethod.GET) public List seletUser(){ return empService.findEmpList(); }}
结果:
Spring MVC4.2 及以上增加了对CORS的支持
时间: 2024-10-10 03:03:07