Spring Boot项目中解决跨域的三种方案

Spring Boot项目中解决跨域的三种方案

1、在目标方法上添加@CrossOrigin注解

“`

@RequestMapping("/list")
@CrossOrigin
public List<Book> list() {
    return this.bookService.list();
}

“`

优点:可以精确到目标方法

缺点:需要为每个方法都添加注解

2、添加CORS过滤器

“`

package cn.itinfor.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration//配置类
public class CorsConfig {

    @Bean
    public CorsFilter CorsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");//允许哪些域
        corsConfiguration.addAllowedHeader("*");//允许哪些请求头
        corsConfiguration.addAllowedMethod("*");//允许哪些请求方法,如:GET、PUT等

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

“`

3、实现WebMvcConfigurer接口,重写addCorsMappings方法

“`

package cn.itinfor.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CordConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTION")
                .allowCredentials(true)//是否允许携带cookie
                .maxAge(3600)//预检请求的有效期,单位为秒,在有效期内不再进行检测
                .allowedHeaders("*");
    }
}

“`

三种方法需单独使用,2、3都使用的情况下,若想其中一个不生效,直接注释掉”@Configuration”即可

Tagged , ,