一、Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等
CORS与JSONP相比
1、 JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。
2、 使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。
3、 JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS
浏览器支持情况
- Chrome 3+
- Firefox 3.5+
- Opera 12+
- Safari 4+
- Internet Explorer 8+
二、在spring MVC 中可以配置全局的规则,也可以使用@CrossOrigin注解进行细粒度的配置。
全局配置:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Configuration
public class CustomCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
};
}
}
|
或者是
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/**
* 全局设置
*
* @author wujing
*/
@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
}
|
定义方法:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/**
* @author wujing
*/
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
|
测试js:
?
|
1
2
3
4
5
6
7
8
9
10
11
|
$.ajax({
url: "http://localhost:8081/api/get",
type: "POST",
data: {
name: "测试"
},
success: function(data, status, xhr) {
console.log(data);
alert(data.name);
}
});
|
细粒度配置
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* @author wujing
*/
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:http://blog.csdn.net/jerome_s/article/details/54731042
相关文章
猜你喜欢
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 81
-
2025-05-25 55
-
Spring boot通过HttpSessionListener监听器统计在线人数的实现代码
2025-05-29 35 -
2025-05-25 64
-
2025-05-29 39
热门评论

