1、使用@CrossOrigin注解实现跨域【局域类跨域】
此注解既可以修饰类,也可以修饰方法。当修饰类时,表示此类中的所有接口都可以跨域;当修饰方法时,表示此方法可以跨域,使用此方式只能实现局部跨域,当一个项目中存在多个类的话,使用此方式就会比较麻烦(需要给所有类上都添加此注解)。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;@RestController
@CrossOrigin(origins = "*")
public class TestController {@RequestMapping("/test")public HashMap<String, Object> test() {return new HashMap<String, Object>() {{put("state", 200);put("data", "success");put("msg", "");}};}
}
2、通过配置文件实现跨域【全局跨域】
创建配置类(@Configuration注解的类),实现WebMvcConfigurer接口,重写addCorsMappings方法,设置允许跨域的代码。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") //所有接口.allowCredentials(true) //是否发送 Cookie.allowedOriginPatterns("*") //支持域.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) //支持的方法.allowedHeaders("*").exposedHeaders("*");}
}
3、通过CorsFilter对象实现跨域【全局跨域】
同样创建配置类(@Configuration注解的类),构造CorsFilter的bean。
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 MyCorsFilter {@Beanpublic CorsFilter corsFilter() {//创建 CORS 配置对象CorsConfiguration config = new CorsConfiguration();//支持域config.addAllowedOriginPattern("*");//是否发送 Cookieconfig.setAllowCredentials(true);//支持请求方式config.addAllowedMethod("*");//允许的原始请求头部信息config.addAllowedHeader("*");//暴露的头部信息config.addExposedHeader("*");//添加地址映射UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**", config);//返回 CorsFilter 对象return new CorsFilter(corsConfigurationSource);}
}
4、通过Response对象实现跨域【局域方法跨域】
此方式是解决跨域问题最原始的方式,但它可以支持任意的 Spring Boot 版本(早期的 Spring Boot 版本也是支持的)。但此方式也是局部跨域,它应用的范围最小,设置的是方法级别的跨域。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;@RestController
public class TestController {@RequestMapping("/test")public HashMap<String, Object> test(HttpServletResponse response) {// 设置跨域response.setHeader("Access-Control-Allow-Origin", "*");return new HashMap<String, Object>() {{put("state", 200);put("data", "success");put("msg", "");}};}
}
5、通过实现 ResponseBodyAdvice 实现跨域【全局跨域】
重写 ResponseBodyAdvice 接口中的 beforeBodyWrite(返回之前重写)方法,此实现方式也是全局跨域,它对整个项目中的所有接口有效。
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {/*** 内容是否需要重写(通过此方法可以选择性部分控制器和方法进行重写)* 返回true表示重写*/@Overridepublic boolean supports(MethodParameter returnType, Class converterType) {return true;}/*** 方法返回之前调用此方法*/@Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,Class selectedConverterType, ServerHttpRequest request,ServerHttpResponse response) {// 设置跨域response.getHeaders().set("Access-Control-Allow-Origin", "*");return body;}
}
6、SpringCloud Gateway中解决跨域
6.1、在 application.yml 或 application.properties 中添加以下配置
spring:cloud:gateway:globalcors:corsConfigurations:'[/**]': #这里的'/**'表示对所有路由生效,可以根据需要调整为特定路径allowedOrigins: "*" #允许所有的源地址,也可以指定具体的域名allowedMethods: #允许的 HTTP 方法类型- GET- POST- PUT- DELETE- OPTIONSallowedHeaders: "*" #允许所有的请求头,也可以指定具体的请求头allowCredentials: true #是否允许携带凭证(cookies)maxAge: 3600 #CORS预检请求的有效期(秒)
6.2、添加 CorsWebFilter 来解决跨域问题
Spring-Framework 5.3 版本之前
@Configuration
public class GlobalCorsConfig {@Beanpublic CorsWebFilter corsWebFilter() {CorsConfiguration config = new CorsConfiguration();//配置为放行所有域名,生产环境请对此进行修改config.addAllowedOrigin("*");//放行的请求头config.addAllowedHeader("*");//放行的请求类型,有GET,POST,PUT,DELETE,OPTIONSconfig.addAllowedMethod("*"); //暴露头部信息config.addExposedHeader("*"); //是否允许发送Cookieconfig.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}
Spring-Framework 5.3 版本之后
@Configuration
public class GlobalCorsConfig {@Beanpublic CorsWebFilter corsWebFilter() {CorsConfiguration config = new CorsConfiguration();//配置为放行所有域名,生产环境请对此进行修改config.addAllowedOriginPattern("*");//放行的请求头config.addAllowedHeader("*");//放行的请求类型,有GET,POST,PUT,DELETE,OPTIONSconfig.addAllowedMethod("*"); //暴露头部信息config.addExposedHeader("*"); //是否允许发送Cookieconfig.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}