關(guān)于springboot2.4跨域配置問題
1、如果只是一個簡單的springboot demo,用以下配置就行
新建config類
```
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author yk
* @date 2021/7/19 14:36
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.maxAge(3600)
.allowCredentials(true);
}
}
```
2、但是實際開發(fā)中我們需要結(jié)合,spring-security、oauth2等等,就會發(fā)現(xiàn)上面的配置失效了,那是因為前面的Filter優(yōu)先級太高了,那我們可以采取如下配置
```
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author yk
* @date 2021/7/19 16:21
*/
@Configuration
public class CrosConfig {
@Bean
public FilterRegistrationBean corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//這里設(shè)置優(yōu)先級最高
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
到此這篇關(guān)于springboot2.4跨域配置的文章就介紹到這了,更多相關(guān)springboot跨域配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot整合PageOffice 實現(xiàn)word在線編輯保存功能
這篇文章主要介紹了Springboot整合PageOffice 實現(xiàn)word在線編輯保存,本文以Samples5 為示例文件結(jié)合示例代碼給大家詳細(xì)介紹,需要的朋友可以參考下2021-08-08
IDEA調(diào)試功能使用總結(jié)(step?over/step?into/force?step?into/step?o
本文主要介紹了IDEA調(diào)試功能使用總結(jié)(step?over/step?into/force?step?into/step?out),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Java實戰(zhàn)之用springboot+netty實現(xiàn)簡單的一對一聊天
這篇文章主要介紹了Java實戰(zhàn)之用springboot+netty實現(xiàn)簡單的一對一聊天,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)Java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
Spring Data JPA 整合QueryDSL的使用案例
QueryDSL 是一個用于構(gòu)建類型安全的 SQL 查詢的 Java 庫,它的主要目標(biāo)是簡化在 Java 中構(gòu)建和執(zhí)行 SQL 查詢的過程,同時提供類型安全性和更好的編碼體驗,對Spring Data JPA 整合QueryDSL使用案例感興趣的朋友跟隨小編一起看看吧2023-08-08
Java BeanPostProcessor與BeanFactoryPostProcessor基礎(chǔ)使用講解
這篇文章主要介紹了Java BeanPostProcessor與BeanFactoryPostProcessor基礎(chǔ)使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-11-11
淺談SpringMVC之視圖解析器(ViewResolver)
本篇文章主要介紹了淺談SpringMVC之視圖解析器(ViewResolver),具有一定的參考價值,有興趣的可以了解一下2017-08-08

