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

2025-04-01 15:50

本文主要是介绍Springboot处理跨域的实现方式(附Demo),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍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.annotawww.chinasem.cntion.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 = newjavascript UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }
}

5. 实战

以下展示项目中的跨域

用 @AutoConfiguration 进行自动配置

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

import org.springframework.boot.autoconfigure.AutoConfiguration;
imwww.chinasem.cnport 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(WebPropertiChina编程es.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); // 对所有路径配置跨域设置

        // 创建并返回一个 FilterRChina编程egistrationBean 实例,注册 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)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持China编程(www.chinasem.cn)。

这篇关于Springboot处理跨域的实现方式(附Demo)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154049

相关文章

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

Java获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取

Spring Boot Actuator应用监控与管理的详细步骤

《SpringBootActuator应用监控与管理的详细步骤》SpringBootActuator是SpringBoot的监控工具,提供健康检查、性能指标、日志管理等核心功能,支持自定义和扩展端... 目录一、 Spring Boot Actuator 概述二、 集成 Spring Boot Actuat

OpenCV在Java中的完整集成指南分享

《OpenCV在Java中的完整集成指南分享》本文详解了在Java中集成OpenCV的方法,涵盖jar包导入、dll配置、JNI路径设置及跨平台兼容性处理,提供了图像处理、特征检测、实时视频分析等应用... 目录1. OpenCV简介与应用领域1.1 OpenCV的诞生与发展1.2 OpenCV的应用领域2

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库

在Java中使用OpenCV实践

《在Java中使用OpenCV实践》用户分享了在Java项目中集成OpenCV4.10.0的实践经验,涵盖库简介、Windows安装、依赖配置及灰度图测试,强调其在图像处理领域的多功能性,并计划后续探... 目录前言一 、OpenCV1.简介2.下载与安装3.目录说明二、在Java项目中使用三 、测试1.测

linux下shell脚本启动jar包实现过程

《linux下shell脚本启动jar包实现过程》确保APP_NAME和LOG_FILE位于目录内,首次启动前需手动创建log文件夹,否则报错,此为个人经验,供参考,欢迎支持脚本之家... 目录linux下shell脚本启动jar包样例1样例2总结linux下shell脚本启动jar包样例1#!/bin

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到