import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//自定义filter,可通过@WebFilter或者在@Configuration注解的配置类中用@Bean注解实例化
public class CrossFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//跨域解决获取前端Origin
String origin = request.getHeader("Origin");
//如果Origin不为空,xxx.com开头
// if (StringUtils.isNotBlank(origin) && origin.indexOf("xxx.com") != -1) {
//设置跨域请求头
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "OPTIONS, POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Request-Headers", "true");
response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, Accept, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
response.addHeader("Access-Control-Max-Age", "3600");
//}
//ajax 提交json数据(比如服务端@RequestBody注解的入参)提交需要加此段代码,放过第一次的OPTIONS请求,否则依然会跨域,建议都加
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(200);
return;
}
//继续向后执行
chain.doFilter(request, response);
}
}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean corsFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new CorsFilter());
filterRegistrationBean.addUrlPatterns("/*");//配置过滤规则
filterRegistrationBean.setName("corsFilter");//设置过滤器名称
filterRegistrationBean.setOrder(1);//执行次序,数字越大,优先级越低
return filterRegistrationBean;
}
Access to XMLHttpRequest at 'http://xxx.yyy.com/queryPage' from origin 'http://zzz.yyy.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.