SpringBoot配置CORS跨域访问

来源:互联网 发布:xyz域名的价值 编辑:程序博客网 时间:2024/06/05 01:03

SpringBoot配置CORS跨域访问

 

添加依赖

<!--CORS只需要添加web依赖即可--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>


创建CORS配置类

CORS配置类必须继承WebMvcConfigurerAdapter

import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter {}


@Override addCorsMappings方法

 

  // 设置跨域访问    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")                .allowedOrigins("*")                .allowedMethods("*")                .allowCredentials(true);    }

说明:

addMapping:可以被跨域的路径,”/**”表示无限制。
allowedMethods:允许跨域访问资源服务器的请求方式,如:POST、GET、PUT、DELETE等“*”表示无限制。
allowedOrigins:”*”允许所有的请求域名访问跨域资源,当设置具体URL时只有被设置的url可以跨域访问。例如:allowedOrigins(“https://www.baidu.com”),则只有https://www.baidu.com能访问跨域资源。

以上只是其中的一部分,具体根据项目需求自定义,不再一一介绍。

附:CorsRegistration源码

public class CorsRegistration {    private final String pathPattern;    private final CorsConfiguration config;    public CorsRegistration(String pathPattern) {        this.pathPattern = pathPattern;        this.config = (new CorsConfiguration()).applyPermitDefaultValues();    }    public CorsRegistration allowedOrigins(String... origins) {        this.config.setAllowedOrigins(Arrays.asList(origins));        return this;    }    public CorsRegistration allowedMethods(String... methods) {        this.config.setAllowedMethods(Arrays.asList(methods));        return this;    }    public CorsRegistration allowedHeaders(String... headers) {        this.config.setAllowedHeaders(Arrays.asList(headers));        return this;    }    public CorsRegistration exposedHeaders(String... headers) {        this.config.setExposedHeaders(Arrays.asList(headers));        return this;    }    public CorsRegistration maxAge(long maxAge) {        this.config.setMaxAge(maxAge);        return this;    }    public CorsRegistration allowCredentials(boolean allowCredentials) {        this.config.setAllowCredentials(allowCredentials);        return this;    }    protected String getPathPattern() {        return this.pathPattern;    }    protected CorsConfiguration getCorsConfiguration() {        return this.config;    }}



原创粉丝点击