SpringBoot 官方文档示例:(56)通过WebMvcConfigurer来配置跨域

本文介绍了如何使用Spring MVC的WebMvcConfigurer接口来配置允许跨域的请求。示例代码展示了如何通过addCorsMappings方法添加允许跨域的路径,如/api/**,并将配置保存到ArrayList中。通过对CorsRegistry的深入理解,可以灵活管理跨域策略。

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

可以通过WebMvcConfigurer来配置跨域的请求

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(proxyBeanMethods = false)
public class MyCorsConfiguration {
  @Bean
  public WebMvcConfigurer corsConfigurer() {
  return new WebMvcConfigurer() {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/api/**");
  }
  };
  }
}

其中addCorsMappings方法中的
registry.addMapping语句用来添加用来跨域的请求地址,本例表示以/api/开头的请求地址都可以跨域

CorsRegistry的源码:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.servlet.config.annotation;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;

public class CorsRegistry {
    private final List<CorsRegistration> registrations = new ArrayList();

    public CorsRegistry() {
    }

    public CorsRegistration addMapping(String pathPattern) {
        CorsRegistration registration = new CorsRegistration(pathPattern);
        this.registrations.add(registration);
        return registration;
    }

    protected Map<String, CorsConfiguration> getCorsConfigurations() {
        Map<String, CorsConfiguration> configs = CollectionUtils.newLinkedHashMap(this.registrations.size());
        Iterator var2 = this.registrations.iterator();

        while(var2.hasNext()) {
            CorsRegistration registration = (CorsRegistration)var2.next();
            configs.put(registration.getPathPattern(), registration.getCorsConfiguration());
        }

        return configs;
    }
}

可见,所有跨域的请求映射是被保存到了一个ArrayList中了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值