Springboot处理跨域的实现方式(附Demo)

 更新时间:2025年04月01日 11:54:39   作者:码农研究僧  
这篇文章主要介绍了Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Springboot处理跨域的方式

1. 基本知识

跨域指的是在一个域下的网页试图访问另一个域下的资源

由于浏览器的同源策略,默认情况下,JavaScript 只能在相同的域中进行请求

跨域通常涉及以下概念:

  • Origin: 包括协议、域名和端口号
    比如 http://example.com:80
  • Same-Origin Policy: 浏览器的安全策略,限制一个源的文档或脚本如何能与另一个源的资源进行交互
  • CORS: 允许跨域请求的机制
    服务器通过设置特定的响应头来告知浏览器哪些源是允许访问的

在 Spring Boot 中,处理跨域的方式有几种,以下是主要的几种方式:

  1. 使用 @CrossOrigin 注解: 这种方式较为简单,适用于控制器层
  2. 配置全局跨域设置: 这种方式适用于全局配置,可以在 Web 配置类中设置
  3. 自定义 CorsConfiguration: 适用于更复杂的跨域配置需求,可以在配置类中自定义

以下为Demo示例

2. @CrossOrigin

可以在控制器类或方法上添加 @CrossOrigin 注解

注解的参数可以配置允许的源(origins)、允许的请求方法(methods)、允许的请求头(allowedHeaders)、是否允许凭证(allowCredentials)等

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyController {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/data")
    public String getData() {
        return "Data from server";
    }
}

如果不使用 @CrossOrigin 注解,浏览器会阻止跨域请求,因为默认的同源策略不允许不同源之间的请求

3. 全局跨域设置

配置 WebMvcConfigurer 来全局设置跨域

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

/**
 * 配置类,用于全局设置 CORS(跨域资源共享)配置
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 配置跨域请求的映射规则
     * 
     * @param registry 用于注册 CORS 配置的注册表
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 添加跨域映射规则
        registry.addMapping("/**")  // 允许所有路径的跨域请求
                .allowedOrigins("http://example.com")  // 允许来自 http://example.com 的跨域请求
                .allowedMethods("GET", "POST", "PUT", "DELETE")  // 允许的请求方法
                .allowedHeaders("*")  // 允许所有请求头
                .allowCredentials(true);  // 允许携带凭证(如 Cookies)
    }
}

4. 自定义 CorsConfiguration

import org.springframework.context.annotation.Bean;
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 CustomCorsConfig implements WebMvcConfigurer {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }
}

5. 实战

以下展示项目中的跨域

用 @AutoConfiguration 进行自动配置

实现WebMvcConfigurer 接口,并通过 FilterRegistrationBean 注册自定义的跨域过滤器 CorsFilter 和其他过滤器

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@AutoConfiguration
@EnableConfigurationProperties(WebProperties.class)
public class WebAutoConfiguration implements WebMvcConfigurer {

    /**
     * 创建一个 CorsFilter 过滤器的 Bean,配置跨域设置
     *
     * @return 配置了跨域设置的 FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterBean() {
        // 创建 CorsConfiguration 对象
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);  // 允许携带凭证(如 Cookies)
        config.addAllowedOriginPattern("*"); // 允许所有来源的请求(注意:生产环境中通常不建议使用 *,应具体配置允许的域)
        config.addAllowedHeader("*"); // 允许所有请求头
        config.addAllowedMethod("*"); // 允许所有 HTTP 方法(GET, POST, PUT, DELETE 等)

        // 创建 UrlBasedCorsConfigurationSource 对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有路径配置跨域设置

        // 创建并返回一个 FilterRegistrationBean 实例,注册 CorsFilter
        return createFilterBean(new CorsFilter(source), Integer.MIN_VALUE);
    }

    /**
     * 创建 DemoFilter Bean,演示模式
     * 
     * @return 配置了 DemoFilter 的 FilterRegistrationBean
     */
    @Bean
    @ConditionalOnProperty(value = "demo", havingValue = "true")
    public FilterRegistrationBean<DemoFilter> demoFilter() {
        // 创建并返回一个 FilterRegistrationBean 实例,注册 DemoFilter
        return createFilterBean(new DemoFilter(), Integer.MIN_VALUE);
    }

    /**
     * 创建 FilterRegistrationBean 实例的通用方法
     * 
     * @param filter 需要注册的过滤器实例
     * @param order  过滤器的执行顺序
     * @return 配置了过滤器的 FilterRegistrationBean 实例
     */
    public static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(order);  // 设置过滤器的顺序
        return bean;
    }
}

总结

处理方式适用场景配置位置灵活性配置难度
@CrossOrigin 注解单个控制器或方法控制器层
全局配置(WebMvcConfigurer)全局设置配置类(WebConfig)
自定义 CorsConfiguration复杂跨域需求配置类(CustomCorsConfig)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 解决	Spring RestTemplate post传递参数时报错问题

    解决 Spring RestTemplate post传递参数时报错问题

    本文详解说明了RestTemplate post传递参数时报错的问题及其原由,需要的朋友可以参考下
    2020-02-02
  • 详解为什么阿里巴巴禁止使用BigDecimal的equals方法做等值比较

    详解为什么阿里巴巴禁止使用BigDecimal的equals方法做等值比较

    这篇文章主要介绍了详解为什么阿里巴巴禁止使用BigDecimal的equals方法做等值比较,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Spring之WEB模块配置详解

    Spring之WEB模块配置详解

    这篇文章主要介绍了Spring之WEB模块配置详解,简单介绍了其继承方式,代理方式,以及相关详细配置代码,具有一定借鉴价值,需要的朋友可以了解下。
    2017-12-12
  • IDEA配置码云Gitee的使用详解

    IDEA配置码云Gitee的使用详解

    这篇文章主要介绍了IDEA配置码云Gitee的使用,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Java解压rar文件的两种实现方法

    Java解压rar文件的两种实现方法

    这篇文章主要介绍了Java解压rar文件的两种实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Java实现数字金额转中文大写金额的完整过程

    Java实现数字金额转中文大写金额的完整过程

    本程序实现将用户输入的整数金额(0~9999999)转换为符合财务规范的中文大写金额,并自动添加单位符号(如“万”、“仟”、“佰”等),例如输入 1234,输出 壹仟贰佰叁拾肆元,文中通过代码示例讲解的非常详细,需要的朋友可以参考下
    2025-04-04
  • springboot2+es7使用RestHighLevelClient的示例代码

    springboot2+es7使用RestHighLevelClient的示例代码

    本文主要介绍了springboot2+es7使用RestHighLevelClient的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • Mybatis中一对多(collection)和一对一(association)的组合查询使用

    Mybatis中一对多(collection)和一对一(association)的组合查询使用

    这篇文章主要介绍了Mybatis中一对多(collection)和一对一(association)的组合查询使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • 图解Java排序算法之堆排序

    图解Java排序算法之堆排序

    这篇文章主要为大家详细介绍了Java经典排序算法之堆排序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • Java验证日期时间字符串是否合法的三种方式

    Java验证日期时间字符串是否合法的三种方式

    判断日期经常合法出现在IO场景下,下面将尽量使用简练的思路和代码呈现给大伙,这篇文章主要给大家介绍了关于Java验证日期时间字符串是否合法的三种方式,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-11-11

最新评论