使用@CrossOrigin注解:
可以为Controller中的方法添加@CrossOrigin注解来允许来自特定源(或所有源)的跨域请求。例如:1
2
3
4
5
6
7
8
9
public class MyController {
public String hello() {
return "Hello World!";
}
}配置WebMvcConfigurer:
在WebMvcConfigurer中配置addCorsMappings()方法,它会将跨域配置应用于整个应用程序。例如:1
2
3
4
5
6
7
8
9
10
public class WebConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}使用Filter过滤器:
实现一个CorsFilter类并继承OncePerRequestFilter类。然后在doFilterInternal方法中设置跨域头。例如:1
2
3
4
5
6
7
8
9
10
11
12
13public class CorsFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "1800");
filterChain.doFilter(request, response);
}
}