一、什么是跨域请求?

跨域请求,就是说浏览器在执行脚本文件的ajax请求时,脚本文件所在的服务地址和请求的服务地址不一样。说白了就是ip、网络协议、端口都一样的时候,就是同一个域,否则就是跨域。这是由于Netscape提出一个著名的安全策略——同源策略造成的,这是浏览器对JavaScript施加的安全限制。是防止外网的脚本恶意攻击服务器的一种措施。

二、SpringBoot工程如何解决跨域问题?

那么如何在SpringBoot中处理跨域问题呢?方法有很多,这里着重讲一种——利用@Configuration配置跨域。 
代码实现如下:

/**
* Created by myz on 2017/7/10.
*
* 设置跨域请求
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
} @Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}

“*”代表全部。”**”代表适配所有接口。 
其中addAllowedOrigin(String origin)方法是追加访问源地址。如果不使用”*”(即允许全部访问源),则可以配置多条访问源来做控制。 
例如:

corsConfiguration.addAllowedOrigin("http://www.aimaonline.cn/");
corsConfiguration.addAllowedOrigin("http://test.aimaonline.cn/");

查看CorsConfiguration类的官方文档(http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html#addAllowedOrigin-java.lang.String-) 
我们可以找到官方对setAllowedOrigins(List allowedOrigins)和addAllowedOrigin(String origin)方法的介绍。

addAllowedOrigin是追加访问源地址,而setAllowedOrigins是可以直接设置多条访问源。 
但是有一点请注意,我查看setAllowedOrigins方法源码时发现,源码如下

public void setAllowedOrigins(List<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins != null?new ArrayList(allowedOrigins):null;
}

根据源码可以得知,setAllowedOrigins会覆盖this.allowedOrigins。所以在配置访问源地址时, 
addAllowedOrigin方法要写在setAllowedOrigins后面,当然了,一般情况下这两个方法也不会混着用。

addAllowedHeader、addAllowedMethod、registerCorsConfiguration方法和addAllowedOrigin的源码差不太多,这里就不一一介绍了。感兴趣的朋友可以自行查阅。

三、其他实现跨域请求方法

当然。除了用这种初始化配置的方法设置跨域问题,在官方的文档中也介绍了其他实现跨域请求的方法(http://spring.io/blog/2015/06/08/cors-support-in-spring-framework)。

例如在接口上使用@CrossOrgin注解:

 @RestController
@RequestMapping("/account")
public class AccountController { @CrossOrigin
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}

对于上述代码,官方给出如下一段说明:

You can add to your @RequestMapping annotated handler method a @CrossOrigin annotation in order to enable CORS on it (by default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation).

意思就是可以直接在@RequestMapping接口上使用@CrossOrigin实现跨域。@CrossOrigin默认允许所有访问源和访问方法。

还有一种方法是直接对整个Controller进行跨域设置:

 @CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController { @GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}

这里,可以对@CrossOrigin设置特定的访问源,而不是使用默认配置。

以上就是对SpringBoot下配实现跨域请求的介绍。


参考文档: 
http://spring.io/blog/2015/06/08/cors-support-in-spring-framework 
http://blog.csdn.net/lovesummerforever/article/details/38052213 
http://blog.csdn.net/lambert310/article/details/51683775

SpringBoot下如何配置实现跨域请求?的更多相关文章

  1. IIS配置支持跨域请求

    对于初次在IIS部署网站的同学,很容易忽略或不知道如何配置使其网站支持跨域请求,这里介绍一个最基础的方式,配置HTTP响应标头. 在IIS上选择HTTP响应标头,选择添加自定义响应标头,通常我们会添加 ...

  2. [二十七]SpringBoot 之 Restful接口的跨域请求

    什么是跨域 简单的说即为浏览器限制访问A站点下的js代码对B站点下的url进行ajax请求.比如说,前端域名是www.abc.com,那么在当前环境中运行的js代码,出于安全考虑,访问www.xyz. ...

  3. SpringBoot配置Cors跨域请求

    一.同源策略简介 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[or ...

  4. nginx配置允许指定域名下所有二级域名跨域请求

    核心原理是根据请求域名匹配是否是某域名的二级域名判断是否添加允许跨越头. #畅游www server { listen 8015; server_name test-tl.changyou.com; ...

  5. vue下axios和fetch跨域请求

    1.在config的index.js下面进行常用跨域配置代码:proxyTable: { '/apis': { //使用"/api"来代替"http://xxxx.cn& ...

  6. django中配置允许跨域请求

    对于django 安装django-cors-headers,详情请看官方文档 pip install django-cors-headers 配置settings.py文件 a.在INSTALLED ...

  7. apache配置跨域请求代理

    1.配置允许跨域请求 Header always set Access-Control-Allow-Origin "*"Header always set Access-Contr ...

  8. jQuery jsonp跨域请求

    跨域的安全限制都是对浏览器端来说的,服务器端是不存在跨域安全限制的. 浏览器的同源策略限制从一个源加载的文档或脚本与来自另一个源的资源进行交互. 如果协议,端口和主机对于两个页面是相同的,则两个页面具 ...

  9. 在ASP.NET 5应用程序中的跨域请求功能详解

    在ASP.NET 5应用程序中的跨域请求功能详解 浏览器安全阻止了一个网页中向另外一个域提交请求,这个限制叫做同域策咯(same-origin policy),这组织了一个恶意网站从另外一个网站读取敏 ...

随机推荐

  1. How use Nmon and "Java Nmon Analyzer" for Monitor Linux Performance

    Nmon is a  resource monitoring tools which can monitor CPU, Memory, Disks, Network and even Filesyst ...

  2. Java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

    在使用response重定向的时候,报以下错误:Java.lang.IllegalStateException: Cannot call sendRedirect() after the respon ...

  3. SSM-网站后台管理系统制作(4)---Ajax前后端交互

    前提:Ajax本身就为前后端交互服务的,实现功能:用户输入信息,实时判断用户的情况,这也是现在登录界面普遍流行的做法.前端js通过注释识别Controller层,该层查询返回,和之前Google验证码 ...

  4. Codeforces 1045B Space Isaac - 数论 - Hash

    题目传送门 传送门I 传送门II 传送门III 题目大意 给定将$\left \{ 0, 1, \dots, m - 1\right \}$分成了不相交的两个非空集合$A$和$B$,给定$A$,问存在 ...

  5. iOS开发 -------- transform属性(形变)

      一 transform属性 在OC中,通过transform属性可以修改对象的平移,比例和旋转角度 常用的创建transform结构体的方法分两大类 (1) 创建"基于控件初始位置&qu ...

  6. JS和Jquery获取和修改label的值

    获取值: label标签在JS和Jquery中使用不能像其他标签一样用value获取它的值: var label=document.getElementById("id");var ...

  7. 异常:unity3d ArgumentException: The Assembly System.Configuration is referenced by System.Data.

    异常:ArgumentException: The Assembly System.Configuration is referenced by System.Data. But the dll is ...

  8. ABAP 中的搜索帮助

    ABAP 中的搜索帮助 https://blog.csdn.net/u011576750/article/details/50999078 一.简介:在abap中,用到的搜索帮助个人遇到的情况如下,进 ...

  9. 转 flowcanvas

    http://blog.sina.com.cn/s/blog_5fb40ceb0102wveq.html Unity 强大的可视化编程插件,Flowcanvas + Nodecanvas 组合(深度修 ...

  10. js数组和数组去重的几种简单的方法

    http://blog.csdn.net/liangklfang/article/details/49300417 1.证明一个对象是数组的方法. 方法(1) [].constructor === A ...