在Spring Boot中实现跨域的几种方式如下:
- 通过CorsFilter实现:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
- 通过配置文件application.properties或application.yml实现:
# application.properties
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.cors.allowed-origins=http://domain2.com
spring.cors.allowed-methods=GET, POST, PUT
spring.cors.allowed-headers=X-Requested-With, content-type
spring.cors.exposed-headers=X-Custom-Header
spring.cors.allow-credentials=true
或者
# application.yml
servlet:
multipart:
max-file-size: 128KB
max-request-size: 128KB
cors:
allowed-origins:
- http://domain2.com
allowed-methods:
- GET
- POST
- PUT
allowed-headers:
- X-Requested-With
- content-type
exposed-headers:
- X-Custom-Header
allow-credentials: true
- 通过@CrossOrigin注解实现:
@CrossOrigin(origins = "http://domain2.com", methods = {RequestMethod.GET, RequestMethod.POST})
@RestController
public class MyController {
// ...
}
- 通过WebMvcConfigurer实现:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("GET", "POST", "PUT")
.allowedHeaders("*")
.allowCredentials(true);
}
}
以上方法可以根据具体需求选择使用,并可以结合在一起使用以提供更全面的跨域支持。