• Spring Boot 跨域解决方案


    Spring Boot 跨域解决方案

    引言

    在 Web 应用中,跨域请求已经成为一个常见的问题。浏览器出于安全考虑,限制了不同源之间的请求,这种限制被称为同源策略。当我们的前端应用和后端 API 部署在不同的域名或端口下时,就会出现跨域问题。为了保证应用的正常运行,解决跨域问题显得尤为重要。本文将介绍两种常见的 Spring Boot 跨域解决方案:WebMvcConfigurerFilterRegistrationBean

    常见的跨域产生条件:

    • 不同的协议:例如,前端使用 HTTPS,后端使用 HTTP。
    • 不同的域名:例如,前端在 example.com,后端在 api.example.com
    • 不同的端口:例如,前端在 localhost:3000,后端在 localhost:8080

    1. 使用 WebMvcConfigurer 解决跨域

    什么是 WebMvcConfigurer?

    WebMvcConfigurer 是 Spring MVC 提供的一个接口,允许我们通过实现该接口来定制 Spring MVC 的配置。它提供了一系列钩子方法,便于我们进行全局配置。

    实现跨域配置的步骤

    下面是通过实现 WebMvcConfigurer 接口来配置跨域的示例代码:

    @Configuration
    public class SpringMvcConfiguration implements WebMvcConfigurer{
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800L);
        }
        
    }
    

    注意事项

    • allowedOrigins:可以指定允许的来源,可以是特定的域名。
    • allowedMethods:指定允许的 HTTP 方法,需根据实际需求配置。
    • allowedHeaders:指定允许的请求头,使用 "*" 表示允许所有请求头,具体可以根据需求进行限制。
    • allowCredentials:是否允许携带凭据(如 Cookies)。

    2. 使用 FilterRegistrationBean 解决跨域

    什么是 FilterRegistrationBean?

    FilterRegistrationBean 是 Spring Boot 提供的用于注册过滤器的工具。通过注册自定义的过滤器,我们可以灵活地处理请求和响应,包括设置跨域相关的响应头。

    实现跨域配置的步骤

    以下是通过 FilterRegistrationBean 实现跨域配置的示例代码:

    @Configuration
    public class CorsConfig {
    
        @Bean
        public FilterRegistrationBean<CorsFilter> corsFilterBean() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowCredentials(true);
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            corsConfiguration.setMaxAge(1800L);
            
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", corsConfiguration);
            
            FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
            bean.setOrder(Integer.MIN_VALUE);
            return bean;
        }
        
    }
    

    结论

    本文介绍了两种在 Spring Boot 中处理跨域请求的方法:使用 WebMvcConfigurerFilterRegistrationBeanWebMvcConfigurer 方法相对简单,适合大多数场景;而 FilterRegistrationBean 方法提供了更大的灵活性,适合需要定制化处理的场景。

  • 相关阅读:
    UE4 / UE5 内存与性能优化
    文件上传漏洞靶场前十关
    数字IC设计 - 逻辑综合简介与Design Compiler使用(GUI方式)
    (Matalb时序预测)GWO-BP灰狼算法优化BP神经网络的多维时序回归预测
    力扣 -- 1218. 最长定差子序列
    基于LLVM13 Enzyme 安装
    时间与日期
    新华三路由器+华为交换机,实现华为交换机指定端口访问外网
    35【源码】数据可视化:基于 Echarts + Python 动态实时大屏 - 门店销售业绩数据中心
    Java版企业电子招标采购系统源码Spring Cloud + Spring Boot +二次开发+ MybatisPlus + Redis
  • 原文地址:https://blog.csdn.net/weixin_43738764/article/details/143382754