小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot 实现跨域的六种方式

行业知识

SpringBoot 实现跨域的六种方式

2026-11-08 23:45:09 来源:互联网转载

目录

1.通过SpringSecurity方式配置

2.使用Spring提供的CorsFilter注入Bean(推荐)

3.使用注解@CrossOrigin注解(繁琐)

4.通过ResponseBodyAdvice 实现跨域

5.通过HttpServletResponse设置跨域

6.通过WebMvcConfigurer 实现跨域


1.通过SpringSecurity方式配置

@Configuration@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {    @Override    protected void configure(HttpSecurity http) throws Exception {        // 允许跨域        http.cors().configurationSource(corsConfigurationSource());        // 省略其他代码...    }    // 跨域配置    private CorsConfigurationSource corsConfigurationSource() {        CorsConfiguration config = new CorsConfiguration();        config.setAllowedMethods(Arrays.asList("GET", "POST"));// 支持请求方式        config.addAllowedOriginPattern("*");// 支持跨域        config.setAllowCredentials(true);// cookie        config.addAllowedHeader("*");// 允许请求头信息        config.addExposedHeader("*");// 暴露的头部信息        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        source.registerCorsConfiguration("/**", config);// 添加地址映射        return source;    }}

2.使用Spring提供的CorsFilter注入Bean(推荐)

//....省略其他代码    @Bean    public CorsFilter corsFilter() {        CorsConfiguration config = new CorsConfiguration();        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));// 支持请求方式        config.addAllowedOriginPattern("*");// 支持跨域        config.setAllowCredentials(true);// cookie        config.addAllowedHeader("*");// 允许请求头信息        config.addExposedHeader("*");// 暴露的头部信息        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        source.registerCorsConfiguration("/**", config);// 添加地址映射        return new CorsFilter(source);    }//....省略其他代码

3.使用注解@CrossOrigin注解(繁琐)

import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; @RestController@CrossOrigin(origins = "*")public class DemoController {    @RequestMapping("/test")    public Object test() {        return "hello world";    }}

4.通过ResponseBodyAdvice 实现跨域

与第5类似

import org.springframework.core.MethodParameter;import org.springframework.http.MediaType;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvicepublic class ResponseAdvice implements ResponseBodyAdvice {    /**     * 内容是否需要重写(通过此方法可以选择性部分控制器和方法进行重写)     * 返回 true 表示重写     */    @Override    public boolean supports(MethodParameter returnType, Class converterType) {        return true;    }    /**     * 方法返回之前调用此方法     */    @Override    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,                                  Class selectedConverterType, ServerHttpRequest request,                                  ServerHttpResponse response) {        // 设置跨域        response.getHeaders().set("Access-Control-Allow-Origin", "*");        return body;    }}

5.通过HttpServletResponse设置跨域

HttpServletResponse#setHeader("Access-Control-Allow-Origin", "*");

6.通过WebMvcConfigurer 实现跨域

import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configurationpublic class CorsConfig implements WebMvcConfigurer {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**") // 所有接口                .allowCredentials(true) // 是否发送 Cookie                .allowedOriginPatterns("*") // 支持域                .allowedMethods(new String[]{"GET", "POST"}) // 支持方法                .allowedHeaders("*")// 允许请求头                .exposedHeaders("*");// 暴露出去的响应头    }}

上一篇:服务器远程协助怎么开?

下一篇:云之讯使用指南,轻松上手,快速掌握操作技巧,成为高手!