springboot解决跨域问题

在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烦恼

posted @   槑孒  阅读(130)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2023-07-25 Ubuntu20.04 文件管理器无法打开
2023-07-25 Ubuntu编译安装GDAL
2023-07-25 CMake Error at CMakeLists.txt: No CMAKE_CXX_COMPILER could be found.
2023-07-25 docker停止所有容器并删除
2023-07-25 ubuntu安装OpenJDK 17,并配置环境变量
2023-07-25 Ubuntu输入su提示认证失败的解决方法
2022-07-25 ArcGIS api for JS三种查询方法比较
点击右上角即可分享
微信分享提示