SpringBoot 实现跨域的六种方式

时间:2025-02-22 14:22:30

目录

1.通过SpringSecurity方式配置

2.使用Spring提供的CorsFilter注入Bean(推荐)

3.使用注解@CrossOrigin注解(繁琐)

4.通过ResponseBodyAdvice 实现跨域

5.通过HttpServletResponse设置跨域

6.通过WebMvcConfigurer 实现跨域


1.通过SpringSecurity方式配置

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 允许跨域
        ().configurationSource(corsConfigurationSource());
        // 省略其他代码...
    }

    // 跨域配置
    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        (("GET", "POST"));// 支持请求方式
        ("*");// 支持跨域
        (true);// cookie
        ("*");// 允许请求头信息
        ("*");// 暴露的头部信息

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        ("/**", config);// 添加地址映射
        return source;
    }

}

2.使用Spring提供的CorsFilter注入Bean(推荐)

//....省略其他代码

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        (("GET", "POST", "PUT", "DELETE"));// 支持请求方式
        ("*");// 支持跨域
        (true);// cookie
        ("*");// 允许请求头信息
        ("*");// 暴露的头部信息

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        ("/**", config);// 添加地址映射
        return new CorsFilter(source);
    }
//....省略其他代码

3.使用注解@CrossOrigin注解(繁琐)

import ;
import ;
import ;
 
@RestController
@CrossOrigin(origins = "*")
public class DemoController {

    @RequestMapping("/test")
    public Object test() {
        return "hello world";
    }
}

4.通过ResponseBodyAdvice 实现跨域

与第5类似

import ;
import ;
import ;
import ;
import ;
import ;
 
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    /**
     * 内容是否需要重写(通过此方法可以选择性部分控制器和方法进行重写)
     * 返回 true 表示重写
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }
    /**
     * 方法返回之前调用此方法
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 设置跨域
        ().set("Access-Control-Allow-Origin", "*");
        return body;
    }
}

5.通过HttpServletResponse设置跨域

HttpServletResponse#setHeader("Access-Control-Allow-Origin", "*");

6.通过WebMvcConfigurer 实现跨域

import ;
import ;
import ;
 
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        ("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods(new String[]{"GET", "POST"}) // 支持方法
                .allowedHeaders("*")// 允许请求头
                .exposedHeaders("*");// 暴露出去的响应头
    }
}