Spring Boot中如何处理跨域请求(CORS)

在Spring Boot中,处理跨域请求(CORS, Cross-Origin Resource Sharing)通常有几种方法。可以通过全局配置、控制器级别的配置或者方法级别的配置来实现。以下是三种常见的方式:

1. 全局配置 CORS

你可以在全局配置中处理跨域请求。这种方法适用于所有控制器和请求。

示例代码:

创建一个 WebConfig 类,并实现 WebMvcConfigurer 接口。

java 复制代码
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 WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许所有路径跨域访问
        registry.addMapping("/**")
                .allowedOrigins("http://xxx.com") // 允许指定域名跨域 
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的HTTP方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true) // 允许携带认证信息
                .maxAge(3600); // 预检请求的缓存时间,单位为秒
    }
}
说明:
  • addMapping("/**"): 允许所有路径的跨域请求。
  • allowedOrigins("http://xxx.com"): 允许来自 http://xxx.com 的跨域请求。
  • allowedMethods(...): 设置允许的 HTTP 方法。
  • allowedHeaders("*"): 允许所有请求头。
  • allowCredentials(true): 允许发送带有凭据的请求。
  • maxAge(3600): 设置预检请求的缓存时间(单位为秒)。

2. 控制器级别 CORS

如果只想为某个特定的控制器或接口方法处理跨域请求,可以使用 @CrossOrigin 注解。

示例代码:
java 复制代码
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    // 允许来自指定域名的跨域请求
    @CrossOrigin(origins = "http://xxx.com")
    @GetMapping("/api/data")
    public String getData() {
        return "Hello Spring Boot";
    }
}
说明:
  • @CrossOrigin: 可以用来标注单个方法或者整个类。上面的例子中,getData() 方法允许来自 http://xxx.com 的跨域请求。
  • 如果你希望为整个控制器的方法添加跨域配置,可以将 @CrossOrigin 放在类上。

3. 方法级别 CORS

你也可以在具体的控制器方法上单独指定 CORS 配置,这样可以更加精细地控制不同方法的跨域行为。

示例代码:
java 复制代码
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AnotherController {

    @CrossOrigin(origins = "http://xxx.com", allowedHeaders = "Content-Type")
    @RequestMapping("/api/data")
    public String getOtherData() {
        return "hello data";
    }
}

总结:

  • 全局配置 适用于需要为整个应用配置跨域支持的场景。
  • 控制器级别配置 适用于为某个控制器的所有方法配置跨域支持的场景。
  • 方法级别配置 适用于为具体的某个方法配置跨域支持的场景。
相关推荐
果果软件5 小时前
2026 后台管理系统选型:若依、JeecgBoot、芋道、NocoBase 和 GewuMind Boot 怎么选?
java·人工智能·后端·ai·开源
码云社区8 小时前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
Sashtok9 小时前
cpp基础知识(10)
c++·后端
摇滚侠9 小时前
《On Java 中文版 基础卷》阅读笔记 接口 18
java·笔记·python
CoderYanger10 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
行百里er10 小时前
【Spring Insight 技术分享】runtime-settings.json 的妙用
后端·开源·监控
databook11 小时前
处理一批 PDF,怎么算真的处理完了
后端·python
苏三说技术12 小时前
为什么越来越多人用 Docling ? - 苏三说技术
后端
nice_lcj52012 小时前
【从零理解计算机网络 · 12】登录态的载体:Cookie、Session、Token 在网络层怎么走
后端·计算机网络·面试·jwt·token·cookie·session
jaysee-sjc12 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven