修改跨域问题

This commit is contained in:
wkeyuan 2022-03-13 22:08:00 +08:00
parent 51ff4d2cc5
commit 64688816d1

View File

@ -1,26 +1,57 @@
package net.diaowen.dwsurvey.config;
import org.apache.catalina.LifecycleState;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 跨域配置类
*/
@Configuration
public class CorsConfig{
public class CorsConfig {
// private static String AllowOrigin = "*";
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowCredentials(true);//sessionid 多次访问一致
corsConfiguration.setAllowedOriginPatterns(getAllowOrigin());
// corsConfiguration.addAllowedOrigin("*");// 允许任何域名使用
corsConfiguration.addAllowedHeader("*");// 允许任何头
corsConfiguration.addAllowedMethod("*");// 允许任何方法postget等
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/file/**", buildConfig());
return new CorsFilter(source);
// source.registerCorsConfiguration("/file/**", buildConfig());
source.registerCorsConfiguration("/**", buildConfig());
CorsFilter corsFilter = new CorsFilter(source);
FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter);
bean.setOrder(0);
return bean;
}
/**
* 可以根据需求调整 AllowOrigin 默认是所有
* @return
*/
public static List<String> getAllowOrigin() {
List<String> list = new ArrayList<>();
list.add("*");//所有域名
return list;
}
}