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";
    }
}

总结:

  • 全局配置 适用于需要为整个应用配置跨域支持的场景。
  • 控制器级别配置 适用于为某个控制器的所有方法配置跨域支持的场景。
  • 方法级别配置 适用于为具体的某个方法配置跨域支持的场景。
相关推荐
wasp5204 分钟前
AgentScope Java 核心架构深度解析
java·开发语言·人工智能·架构·agentscope
2501_9167665413 分钟前
【Springboot】数据层开发-数据源自动管理
java·spring boot·后端
半夏知半秋24 分钟前
docker常用指令整理
运维·笔记·后端·学习·docker·容器
程序员码歌29 分钟前
短思考第263天,每天复盘10分钟,胜过盲目努力一整年
android·前端·后端
自在极意功。30 分钟前
MyBatis 动态 SQL 详解:从基础到进阶实战
java·数据库·mybatis·动态sql
软件管理系统39 分钟前
基于Spring Boot的便民维修管理系统
java·spring boot·后端
源代码•宸1 小时前
Leetcode—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展
百***78751 小时前
Step-Audio-2 轻量化接入全流程详解
android·java·gpt·php·llama
快乐肚皮1 小时前
MySQL递归CTE
java·数据库·mysql·递归表达式