当前位置: 首页 > news >正文

SpringBoot项目中解决CORS跨域资源共享问题

在Spring Boot项目中解决CORS(跨域资源共享)问题,可以通过以下几种方法:

1. 使用@CrossOrigin注解

这是最简单的方法,适用于单个控制器或控制器方法级别的跨域配置。你可以在控制器类或具体的方法上使用@CrossOrigin注解来允许跨域请求。

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://localhost:3000") // 允许指定域名的跨域请求@GetMapping("/example")public String example() {return "Example Response";}
}

 

你也可以使用通配符*来允许所有域名的跨域请求,但出于安全考虑,生产环境中应该明确允许的域名。

2. 全局跨域配置

通过实现WebMvcConfigurer接口并重写addCorsMappings方法,可以设置全局的CORS配置。这种方法会影响所有未明确拒绝的跨域请求。

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 {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 允许跨域的路径.allowedOrigins("http://localhost:3000") // 允许的域名.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法.allowedHeaders("*") // 允许的头信息.allowCredentials(true) // 是否允许证书(cookies).maxAge(3600); // 预检请求的缓存时间}
}


同样,你也可以使用通配符*来允许所有域名,但请注意安全风险。

3. 使用CorsFilter

创建一个CorsFilter过滤器,并在Spring Boot中注册它。这种方法可以在Spring Security中使用,或者直接在Spring Boot中使用。

import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Component
public class CorsFilter implements Filter {@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res;HttpServletRequest request = (HttpServletRequest) req;response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {response.setStatus(HttpServletResponse.SC_OK);} else {chain.doFilter(req, res);}}
}


4. 使用Spring Security配置跨域

如果你的项目中使用了Spring Security,可以在配置类中添加CORS配置。

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors().and() // 启用CORS配置// 其他安全配置....csrf().disable(); // 禁用CSRF(如果需要)}
}


然后,你还需要确保在Spring Security的配置中添加了CORS过滤器,或者通过上面的.cors()方法启用了CORS支持。

5. 使用application.propertiesapplication.yml配置

你也可以在Spring Boot的配置文件中添加全局的CORS配置。

application.properties中:

# 允许跨域的地址
cors.allowed-origins=http://localhost:3000
# 允许的方法
cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
# 允许的头部
cors.allowed-headers=origin,content-type,accept,x-requested-with
# 允许发送Cookie
cors.allow-credentials=true
# 预检请求的有效期,单位为秒
cors.max-age=3600


然而,需要注意的是,直接在application.propertiesapplication.yml中配置CORS可能不是Spring Boot推荐的做法,因为这种方式不如使用Java配置类那样灵活和可维护。通常,建议使用前面提到的方法之一来配置CORS。

总结

在Spring Boot项目中解决CORS问题有多种方法,你可以根据项目的具体需求和安全考虑来选择合适的方法。通常,使用@CrossOrigin注解或全局跨域配置是最常见和推荐的做法。如果你使用了Spring Security,还需要确保在Spring Security的配置中正确启用了CORS支持。

http://www.lryc.cn/news/521566.html

相关文章:

  • Android string.xml中特殊字符转义
  • 解析传统Workflow、AI Workflow与AI Agent概念,并通过Coze案例探讨利用AI工作流构建应用的实践流程
  • 光谱相机的光谱分辨率可以达到多少?
  • android Recyclerview viewholder统一封装
  • Windows部署NVM并下载多版本Node.js的方法(含删除原有Node的方法)
  • 51单片机入门基础
  • 老centos7 升级docker.io为docker-ce 脚本
  • 数仓建模(三)建模三步走:需求分析、模型设计与数据加载
  • PHP xml 常用函数整理
  • 数据结构(Java版)第八期:LinkedList与链表(三)
  • 数据结构学习记录-数据结构概念
  • 【Linux】11.Linux基础开发工具使用(4)
  • 数据结构与算法之栈: LeetCode 1047. 删除字符串中的所有相邻重复项 (Ts版)
  • C++ 在线编译软件介绍、杭电OJ、北大OJ、力扣OJ
  • Java学习笔记(二十三)
  • 《AI赋能鸿蒙Next,开启智能关卡设计新时代》
  • js:正则表达式
  • linux环境使用docker部署多个war项目
  • 【react】使用antd Table渲染数据遇到的报错问题
  • JVM之垃圾回收器G1概述的详细解析
  • 1.15寒假作业
  • RK356x bsp 5 - 海华AW-CM358SM Wi-Fi/Bt模组调试记录
  • 支持Google Analytics快捷添加的CMS:费用与部署形式详解
  • CSS | 实现三列布局(两边边定宽 中间自适应,自适应成比)
  • fpga系列 HDL:跨时钟域同步 双触发器同步器
  • 金融项目实战 05|Python实现接口自动化——登录接口
  • 《HTML在网络安全中的多面应用:从防范攻击到安全审查》
  • Linux网络 | 学习传输层网络协议之UDP(短篇)
  • iOS - 内存屏障的使用场景
  • MySQL 8.0 新特性详解与实用示例