Spring Boot解决跨域的五种方式
在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);
}
- 通过@CrossOrigin注解
在Controller或者具体的方法上添加@CrossOrigin注解。
@CrossOrigin(origins = "*")
@RestController
public class MyController {
// ...
}
- 通过WebMvcConfigurer
实现WebMvcConfigurer接口,并重写addCorsMappings方法。
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
- 通过HttpServletRequest包装
创建一个继承自HttpServletRequestWrapper的类,然后在过滤器中使用。
public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final String origin;
public CustomHttpServletRequestWrapper(HttpServletRequest request, String origin) {
super(request);
this.origin = origin;
}
@Override
public String getHeader(String name) {
if ("Origin".equalsIgnoreCase(name)) {
return origin;
}
return super.getHeader(name);
}
}
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(
httpServletRequest, "http://localhost:8081");
chain.doFilter(wrappedRequest, response);
}
}
- 使用Response Header设置Access-Control-Allow-Origin
在Controller的具体方法中,通过设置响应头来实现跨域。
@RestController
public class MyController {
@GetMap
评论已关闭