SpringBoot 跨域问题处理

博客介绍了在Spring Boot中实现CORS的三种方式。一是使用@CrossOrigin注解,可添加在方法或类上;二是编写配置类,能对全局接口起作用;三是编写Filter,可手动指定对哪些接口有效,且这三种方式均经过亲测。

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


处理SpringBoot跨域的三种方式

1.使用注解

使用@CrossOrigin 注解实现
如果想要对某一接口配置 CORS,可以在相应的方法上添加 @CrossOrigin 注解,如下,只针对此接口起作用,别的接口还是不能跨域使用

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

    @CrossOrigin(origins = {"http://localhost:8086", "null"})
    @ApiOperation("测试")
    @RequestMapping("/hello")
    public R test(){

        return R.ok().data("msg","Hello World!");
    }
}

如果想要对某一类中的接口配置 CORS,可以在相应的类上添加 @CrossOrigin 注解,如下,只针对此类中的所有接口起作用,别的类下方的接口还是不能跨域使用

@RestController
@RequestMapping("/test")
@CrossOrigin
public class RootController {
    @ApiOperation("测试")
    @RequestMapping("/hello")
    public R test(){

        return R.ok().data("msg","Hello World!");
    }
}
2.编写配置类实现

对全局的接口都起作用

package com.org.comunity.config;
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 CrossConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}
3.编写Filter实现

可以通过添加 Filter 的方式,配置 CORS 规则,并手动指定对哪些接口有效

import org.springframework.boot.web.servlet.FilterRegistrationBean;
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 MyConFiguration {

    @Bean
    public FilterRegistrationBean crosFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:8080");//指定你自己的接口
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

上面三种方式亲测有效,欢迎大家批评斧正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值