#新增一个过滤器类并实现filter接口
public class CorsFilter implements Filter {
final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
System.out.println("*********************************过滤器被使用**************************");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
# 配置过滤器使其生效,注意的是需要放在所有过滤器之前(注意:如果有其他过滤器必须配置@order()注解,让优先级为最高,如果不配置的优先级会出现跨域问题。)
@Bean
@Order(1)
public FilterRegistrationBean crosFilter() {
System.out.println("初始化跨域过滤器开始==================================");
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
com.liushun.common.filter.CorsFilter crCorsFilter = new com.liushun.common.filter.CorsFilter();
registrationBean.setFilter(crCorsFilter);
return registrationBean;
}