zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringBoot实现配置跨域请求

SpringBoot配置跨域 实现 请求
2023-09-11 14:16:37 时间

一、什么是跨域请求?

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

下面是几个跨域的例子:

http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)

http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)

http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)

http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)

http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

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

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

/**
 *
 * 设置跨域请求
 */
@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默认允许所有访问源和访问方法。

上面是对方法运用注解,还可以这样:

//@CrossOrigin  表示所有的URL均可访问此资源
@CrossOrigin(origins = "http://127.0.0.1:8093")//表示只允许这一个url可以跨域访问这个controller
@RestController
@RequestMapping("/testCorss")
public class CorssOriginController {

    //可以对方法运用该注解
    //@CrossOrigin(origins = "http://127.0.0.1:8093")
    @GetMapping("/getString")
    public String getString(){
        return "跨域成功!";
    }

}

代码说明:总的来说,@CrossOrigin这个注解用起来很方便,这个可以用在方法上,也可以用在类上。如果你不设置他的value属性,或者是origins属性,就默认是可以允许所有的URL/域访问。

  • value属性可以设置多个URL。
  • origins属性也可以设置多个URL。
  • maxAge属性指定了准备响应前的缓存持续的最大时间。就是探测请求的有效期。
  • allowCredentials属性表示用户是否可以发送、处理 cookie。默认为false
  • allowedHeaders 属性表示允许的请求头部有哪些。
  • methods 属性表示允许请求的方法,默认get,post,head。

还有一种方法(第三种跨域方法)是直接对整个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下配实现跨域请求的介绍。下面ref也有其他跨域方法,也写得不错,给个参考!!!


ref: 

(20条消息) SpringBoot解决跨域的5种方式_wh柒八九的博客-CSDN博客_springboot解决跨域
http://spring.io/blog/2015/06/08/cors-support-in-spring-framework