解决方案
1.(使用框架提供好的CorsFilter,它继承了OncePerRequestFilter,又实现了Filter接口):
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class LeyouCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
config.addAllowedOrigin(“http://manage.leyou.com”);
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod(“OPTIONS”);
config.addAllowedMethod(“HEAD”);
config.addAllowedMethod(“GET”);
config.addAllowedMethod(“PUT”);
config.addAllowedMethod(“POST”);
config.addAllowedMethod(“DELETE”);
config.addAllowedMethod(“PATCH”);
// 4)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
注意:我们也可以自己定义CrosFilter去实现FIlter接口,解决跨域问题。这时不要导入import org.springframework.web.filter.CorsFilter框架给我们提供的这个过滤器了。
写法类似这样子:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
-
@author zhanghui
-
@date 2019/7/2
*/
@Component
public class CorsFilter implements Filter {private final Logger log = LoggerFactory.getLogger(CorsFilter.class);
public CorsFilter() {
log.info(“SimpleCORSFilter init”);
}@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (request.getHeader("Origin") != null) { response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); } response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me"); chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}@Override
public void destroy() {
}
}
点击查看别人总结的解决跨域访问的方法