- 设计
- 跨域三件套
- AxiosCorsFilter
- ClassCorsConfig
- InterceptorConfig
- 路由映射
- 接口实现
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AxiosCorsFilter extends CorsFilter {
public AxiosCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return source;
}
}
ClassCorsConfig
@Configuration
public class ClassCorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration =new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
// UrlBasedCorsConfigurationSource source= new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", buildConfig()); // 4
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true);
//允许cookies跨域
config.addAllowedOrigin("*");
// 允许向该服务器提交请求的URI,*表示全部允许。。这里尽量限制来源域,比如http://xxxx:8080 ,以降低安全风险。。
config.addAllowedHeader("*");
// 允许访问的头信息,*表示全部 com.cxl.rc.smart.config.setMaxAge(18000L);
//预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("*");
//允许提交请求的方法,*表示全部允许,也可以单独设置GET、PUT等 com.cxl.rc.smart.config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
// 允许Get的请求方法
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**",config);
return new CorsFilter(source);
}
}
InterceptorConfig
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET,POST,PUT,DELETE,HEAD,OPTIONS")
.allowedHeaders("*")
.allowCredentials(false).maxAge(3600);
}
@Override
public void extendMessageConverters(List> converters) {
converters.add(responseBodyConverter());
}
@Bean
public HttpMessageConverter responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
}
路由映射
public class RouterConfig {
private static Map config = new HashMap<>();
static {
// key是匹配的前缀
config.put("/api","http://你要跳转的ip:端口");
}
public static String match(String path) throws Exception{
Set strings = config.keySet();
String s = null;
for (String string : strings) {
boolean equals = path.startsWith(string);
if(equals){
s = config.get(string);
}
}
if(null == s){
throw new Exception("["+ path +"]没有找到指定路由");
}
return s;
}
public static String get(String path) throws Exception{
Set strings = config.keySet();
for (String string : strings) {
boolean equals = path.startsWith(string);
if(equals){
return string;
}
}
throw new Exception("["+ path +"]没有找到指定映射");
}
}
接口实现
只是简单的实现而已,满足当前项目的需求。并没有做太多的完善,勿杠谢谢。
@RequestMapping("**")
public Object requests(@RequestBody(required = false) Map data, HttpServletRequest request, HttpServletResponse response) throws Exception{
String path = request.getServletPath();
String url = path.replaceFirst(RouterConfig.get(path), RouterConfig.match(path));
if(request.getParameterMap().size() > 0){
StringBuffer params = new StringBuffer(url + "?");
Map r = request.getParameterMap();
for (String s : r.keySet()) {
params.append(s+"="+request.getParameter(s));
}
url = params.toString();
}
System.out.println("router >>>["+path+"] >>>>> ["+url+"]");
HttpRequest req = HttpUtil.createRequest(Method.valueOf(request.getMethod()), url);
req.header("token",request.getHeader("token"));
req.header("Content-Type",request.getHeader("Content-Type"));
req.header("Accept",request.getHeader("Accept"));
req.header("Host",request.getHeader("Host"));
req.header("User-Agent",request.getHeader("User-Agent"));
if(null != data) {
req.body(JSONUtil.toJsonStr(data));
}
if(url.indexOf("download")>-1){
response.getOutputStream().write(req.execute().bodyBytes());
return "file download success~!";
}else{
return req.execute().body();
}
}



