在需要跨域的整个Controller或者单个方法上添加@CrossOrigin注解
1 @Configuration 2 public class WebMvcConfig extends WebMvcConfigurerAdapter { 3 @Override 4 public void addCorsMappings(CorsRegistry registry) { 5 registry.addMapping("/**") 6 .allowedOrigins("*") 7 .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") 8 .maxAge(3600) 9 .allowCredentials(true); 10 } 11 }
1 @Component 2 @WebFilter(urlPatterns = "/*", filterName = "authFilter") //这里的“/*” 表示的是需要拦截的请求路径 3 public class PassHttpFilter implements Filter { 4 @Override 5 public void init(FilterConfig filterConfig) throws ServletException { } 6 @Override 7 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 8 HttpServletResponse httpResponse = (HttpServletResponse)servletResponse; 9 httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept"); 10 httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); 11 httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080"); 12 filterChain.doFilter(servletRequest, httpResponse); 13 } 14 @Override 15 public void destroy() { } 16 }
原文:https://www.cnblogs.com/yhcjhun/p/10879690.html