首页 > 其他分享 >springboot解决跨域问题

springboot解决跨域问题

时间:2024-07-25 21:07:08浏览次数:6  
标签:springboot cors springframework public org 解决 import annotation 跨域

在Spring Boot中解决跨域问题(CORS, Cross-Origin Resource Sharing)有多种方法。

这里介绍几种常用的方法:

方法一:使用全局配置

可以在Spring Boot的配置类中使用WebMvcConfigurer接口来配置全局的CORS策略。

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://example.com") // 允许的来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD") // 允许的方法
                .allowedHeaders("*") // 允许的头部
                .allowCredentials(true) // 是否允许发送Cookie
                .maxAge(3600); // 预检请求的有效期,单位为秒
    }
}

方法二:使用注解配置

也可以在控制器类或者方法上使用@CrossOrigin注解来配置CORS。

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://example.com")
    @GetMapping("/example")
    public String example() {
        return "Hello, World!";
    }
}

方法三:使用过滤器配置

通过创建一个过滤器来配置CORS也是一种方法。

import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        response.setHeader("Access-Control-Allow-Origin", "http://example.com");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

方法四:在Spring Security中配置

如果Spring Boot应用中使用了Spring Security,还需要在Spring Security的配置类中配置CORS。

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        // 其他的安全配置
        return http.build();
    }
}

方法五:结合Spring Boot的application.properties文件配置

application.properties文件中添加以下配置:

# 允许跨域的地址
cors.allowed-origins=http://example.com

# 允许的方法
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

然后在Spring Boot的配置类中读取这些配置:

import org.springframework.beans.factory.annotation.Value;
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 {

    @Value("${cors.allowed-origins}")
    private String[] allowedOrigins;

    @Value("${cors.allowed-methods}")
    private String[] allowedMethods;

    @Value("${cors.allowed-headers}")
    private String[] allowedHeaders;

    @Value("${cors.allow-credentials}")
    private boolean allowCredentials;

    @Value("${cors.max-age}")
    private long maxAge;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(allowedOrigins)
                .allowedMethods(allowedMethods)
                .allowedHeaders(allowedHeaders)
                .allowCredentials(allowCredentials)
                .maxAge(maxAge);
    }
}

选择哪种方法取决于具体需求和项目架构。

如果需要跨域配置全局有效,推荐使用全局配置的方法;

如果只针对特定的控制器或方法,使用注解配置会更简洁。

Spring Boot 3跨域方案详解:告别CORS烦恼

标签:springboot,cors,springframework,public,org,解决,import,annotation,跨域
From: https://www.cnblogs.com/echohye/p/18324138

相关文章

  • SpringBoot集成RocketMQ
    RocketMQ的延迟消息概述举例说明延迟:PDD的拼单,大家在pdd拼单购买商品时,下单后,会有一个拼单倒计时,如果在倒计时结束的时候,还未拼单成功,那么系统就会取消到这个订单。技术实现:只需在消息生产者代码中添加一句:message.setDelayTimeLevel(3);//设置延迟的等级,即消费者接收到......
  • 首页高并发案例遇到的问题以及解决办法
    要通过openresty,ngin,MySQL和redis来部署一个项目首先需要安装以上工具安装openrestyyumintsallyum-utilsyum-config-manager--add-repohttps://openresty.org/package/centos/openresty.repo首先执行这两行代码然后就可以执行安装命令yuminstallopenresty-y在安......
  • 一行CSS解决难倒工程师两天的问题!
    遇到了一个非常奇怪的问题。首页用swiper实现了几个栏目的选项卡,然后在推荐栏,是滚动加载的瀑布流。出现了一个问题,在移动端(PC上不会),左右滑动切换栏目的时候,swiper卡住了,如果上下滑动的时候,稍稍有一点倾斜,也会触发swiper的左右滑动,但是会滑到一半卡住!swiper这样一个成熟的组件,不......
  • 无法解析插件 org.apache.maven.plugins:maven-war-plugin:3.2.3(已解决)
    文章目录1、问题出现的背景2、解决方法1、问题出现的背景最开始我想把springboot项目转为javaweb项目,然后我点击下面这个插件就转为javaweb项目了,但是我后悔了,想要还原成springboot项目,点开项目结构关于web的都移除了,还是不行,控制台报下面的错误无法解析插件org.......
  • SpringBoot 日志
    目录一、日志概述二、日志使用2.1打印日志2.2日志格式2.3日志级别2.4日志配置2.4.1日志级别2.4.2日志持久化2.4.3日志文件分割2.4.4配置日志格式三、更简单的日志输出3.1添加lombok依赖3.2输出日志一、日志概述在SpringBoot项目启动后,项目本身就......
  • 【经典问题】精析:一文搞懂 动态规划解决 0-1背包问题
    背包问题核心元素:数量为n的物品,容量为size的背包,给出每个物品的重量weight和价值val,求背包能装的物品最大总价值。求解思路的本质:从小体量(少物品,少容量)的问题开始,不断求出局部最优解,然后以此为基础放大问题(求得较多物品,较大容量下最优解)重复上述过程,直到求出题目要求的最优......
  • Easyconnect登录提示:拉起虚拟网卡失败 解决办法
    原文链接:https://www.cnblogs.com/runningwind/p/17532438.html用户使用easyconnect登录SSLVPN后提示:拉起虚拟网卡失败,请确保虚拟网卡已经安装在系统上并处于启用状态 设备管理器查看虚拟网卡一直有感叹号 尝试更新网卡驱动及启用禁用虚拟网卡,不行尝试使用SSLVPN诊断修......
  • 《Apex英雄》提示缺少mileswin64.dll文件怎么处理?EA平台启动游戏找不到mileswin64.dll
    当EA平台启动游戏时提示找不到mileswin64.dll文件,您可以尝试以下解决方法。首先,重新安装游戏以确保相关文件完整。其次,检查系统是否存在病毒或恶意软件并进行清理。还可以更新驱动程序和系统组件。本篇将为大家带来EA平台启动游戏找不到mileswin64.dll文件解决方法的内容,感兴趣......
  • 解决npm安装electron失败的问题
    1.问题描述使用npm创建项目后,添加electron依赖npminstallelectron--save-dev一直报错,部分报错日志如下484sillyauditerror[objectObject][email protected]{code:1,signal:null}487verbosestac......
  • SpringBoot 依赖之Java Mail Sender邮件发送
    JavaMailSender依赖名称:JavaMailSender功能描述:SendemailusingJavaMailandSpringFramework’sJavaMailSender.使用JavaMail和SpringFramework的JavaMailSender发送电子邮件。<dependency> <groupId>org.springframework.boot</groupId> <artifa......