Springboot 为RESTful Web服务启用Cors跨源请求 的四种方式

本文详述了SpringBoot中解决CORS跨域问题的四种常见方法:配置CorsFilter、重写WebMvcConfigurer、使用@CrossOrigin注解及手动设置响应头。适合不同版本的SpringMVC和SpringBoot。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自 springboot设置Cors跨域的四种方式

前言:CorsFilter / WebMvcConfigurer / @CrossOrigin 需要SpringMVC 4.2
以上的版本才支持,对应SpringBoot 1.3 版本以上都支持这些CORS特性。不过,使用SpringMVC4.2
以下版本的小伙伴也不用慌,直接使用方式4通过手工添加响应头来授权CORS跨域访问也是可以的。

方式1:返回新的CorsFilter

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
 
 
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(3600L);
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
 
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

方式2:重写WebMvcConfigurer

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                //**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
                .allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }
}

方式3:使用注解(@CrossOrigin)

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
 
 
@RestController
@RequestMapping("/hello")
@CrossOrigin  //较粗的 controller粒度
public class HelloController {

		@GetMapping
		@CrossOrigin(origins = "http://localhost:9000")  //较细的 method 粒度
		public Object hello() {
			return "Hello World~";
		}
 
}

方式4:手工设置响应头(HttpServletResponse )

这种方式,可以自己手工加到,具体的controller,inteceptor,filter等逻辑里

@RestController
@RequestMapping("/test")
public class TestController {

		@GetMapping
		public String test(HttpServletResponse response){
			response.addHeader("Access-Control-Allow-Origin", "*");
		return "success";
		}
}

总结:以上是设置cors跨域后端解决的四种方式,本质都是类似最后一种设置响应头,不过都是各自包实现了不同的封装逻辑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值