跨域AJAX请求
在处理跨域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的支持
一个应用可能会有多个 CORS 配置,并且可以设置每个 CORS 配置针对一个接口或一系列接口或者对所有接口生效
如果想要对某一接口配置 CORS,可以在方法上添加 CrossOrigin 注解:
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
return "{\"project\":\"just a test\"}";
}
如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效
@CrossOrigin(origins = {"http://localhost:8080", "null"})
@RestController
public class HomeController{
}
全局配置,则需要添加一个配置类
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:9000", "null")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
也可以通过添加 Filter 的方式,配置 CORS 规则,并手动指定对哪些接口有效
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:9000");
config.addAllowedOrigin("null");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
也可以修改配置文件
<mvc:cors> <mvc:mapping path="/**" allowed-origins="http://127.0.0.1:8020" allowed-methods="POST,GET, OPTIONS,DELETE,PUT" allowed-headers="Content-Type,ContentType,Access-Control-Allow-Headers, Authorization, X-Requested-With" allow-credentials="true"/> </mvc:cors>
本文作者:黎华扬
本文链接:https://www.cnblogs.com/galenblog/p/8034681.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步