Spring Boot项目跨域问题解决方案详解-五种方案(附实战代码)

一、什么是跨域问题?
跨域问题(CORS,Cross-Origin Resource Sharing)是由浏览器的同源策略引起的安全机制。当前端请求的协议(http/https)、域名(IP)或端口与当前页面不一致时,浏览器会拦截响应结果,导致前端无法获取数据。

示例场景:
前端运行在 http://localhost:8080,后端接口在 http://localhost:9090,此时浏览器会拦截请求。

二、5种Spring Boot跨域解决方案
1. 使用@CrossOrigin注解(局部配置)
在Controller类或方法上添加注解,允许指定接口跨域。

@RestController
public class UserController {
    
    // 允许所有来源访问该接口
    @CrossOrigin(origins = "*")
    @GetMapping("/user")
    public String getUser() {
        return "User Info";
    }

    // 指定允许的来源和HTTP方法
    @CrossOrigin(origins = "http://localhost:8080", methods = RequestMethod.POST)
    @PostMapping("/update")
    public String updateUser() {
        return "Update Success";
    }
}
2. 全局配置(推荐)
通过实现WebMvcConfigurer接口配置全局跨域规则。

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 所有接口
                .allowedOriginPatterns("*") // 允许所有来源(生产环境建议指定具体域名)
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的HTTP方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true) // 允许携带Cookie
                .maxAge(3600); // 预检请求缓存时间(秒)
    }
}

3. 过滤器配置
通过自定义过滤器处理跨域。

@Configuration
public class CorsFilterConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        config.addAllowedOriginPattern("*");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

4. 返回新的CorsFilter(适合Spring Security项目)
在Spring Security配置中处理跨域。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and() // 启用CORS
            .csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        config.setAllowedMethods(Arrays.asList("GET", "POST"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

5. 手动设置响应头
在接口中手动添加响应头(不推荐,适用于临时测试)。

@RestController
public class TestController {

    @GetMapping("/test")
    public ResponseEntity<String> test() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        return new ResponseEntity<>("Test", headers, HttpStatus.OK);
    }
}

三、总结:最常用的解决方案
全局配置(方法2) 是最常用的方式,优点如下:

配置简单:统一管理所有接口的跨域规则。
灵活可控:支持细粒度配置来源、方法、头信息等。
适合前后端分离项目:无需在每个接口上单独添加注解。
四、注意事项
生产环境中应将allowedOrigins替换为具体的前端域名(如http://www.example.com)。
如果使用Spring Security,需额外在安全配置中启用CORS。
allowCredentials(true)时,不能使用allowedOrigins("*"),需改为allowedOriginPatterns("*")或指定具体域名。
通过以上方法,可轻松解决Spring Boot项目中的跨域问题,建议根据实际场景选择最合适的方案!

                        
原文链接:https://blog.csdn.net/baidu_34422713/article/details/146609560

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值