直接拿去用
1,Aop
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
public class ControllerAOP {
public Object corsAop(ProceedingJoinPoint pro) throws Throwable {
System.out.println("=====================");
//获取response
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//核心设置
response.setHeader("Access-Control-Allow-Origin", "*");
//执行调用的方法
Object proceed = pro.proceed();
return proceed;
}
}
2.filter
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 CorsConfig {
/**
配置允许跨域访问的ip--从这些url发过来的请求,都是允许支持的跨源请求 ip与域名会被当成两个不同的url
*/
private static String[] orginVal=new String[]{
"localhost:9527",
"127.0.0.1:9527",
"39.106.116.51:8082",
"192.180.181.3:9081",
"192.180.181.3:9080",
"27.196.158.173:9080",
"27.196.158.173:19080",
"localhost:8082",
"127.0.0.1:8082"
};
private void addAllowedOrigins(CorsConfiguration corsConfiguration){
corsConfiguration.addAllowedOrigin("*");
// for(String origin:orginVal){
// //不同协议也是不同的url
// corsConfiguration.addAllowedOrigin("http://"+origin);
// corsConfiguration.addAllowedOrigin("https://"+origin);
// }
}
/**
* 项目加载时,把过滤器生成,来统一管理跨源请求(不用再在每个controller上单独配置)
* @return
*/
@Bean
public CorsFilter corsFilter(){
//配置跨域访问的过滤器
//基于url的数据源
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration=new CorsConfiguration();
//把允许的跨域源添加到corsConfiguration中
this.addAllowedOrigins(corsConfiguration);
// corsConfiguration.addAllowedOrigin("*");
//不对method做限制,允许所有method请求(get,post....)
corsConfiguration.addAllowedMethod("*");
//不对head做限制
corsConfiguration.addAllowedHeader("*");
//允许跨域访问(在响应报文里带上跨域请求的凭证,和浏览器请求里面xhrFields相匹配,前后端才能正常通信)
corsConfiguration.setAllowCredentials(true);
//指定对当前这个服务下的所有请求都启用corsConfiguration的配置
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
}