注意: CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上。
1.重写WebMvcConfigurer(全局跨域)
import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 全局配置,解决跨域 */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"). //允许跨域的域名,可以用*表示允许任何域名使用 allowedOrigins("*"). //允许任何方法(post、get等) allowedMethods("*"). //允许任何请求头 allowedHeaders("*"). //带上cookie信息 allowCredentials(true). //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果 exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); } }
2.通过实现Fiter
接口在请求中添加一些Header
来解决跨域的问题
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("Access-Control-Allow-Credentials", "true"); res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) { response.getWriter().println("ok"); return; } chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } }