springboot过滤器执行两次的解决及跨域过滤器

在进行springboot整合过滤器的过程中可能会遇到过滤器执行两次的问题,针对这个问题可能出现的一种原因就是因为在请求执行完之后浏览器会再发一次请求.ico的请求,解决的方法就是在执行过滤器方法之前再加一层判断就好了.

HttpServletRequest request = (HttpServletRequest)servletRequest;
if (request.getRequestURL().toString().matches(".+.ico$")) {
     filterChain.doFilter(servletRequest, servletResponse);
 } else {
     // do something yourself
     filterChain.doFilter(servletRequest, servletResponse);
 }

在不使用框架提供的跨域的方案的情况下可以自己注册一个通用的跨域请求过滤器,具体的代码如下
首先先注册一个过滤器到springboot

@Bean
    public FilterRegistrationBean corsFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        CorsFilter corsFilter = new CorsFilter();
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setFilter(corsFilter);
        return filterRegistrationBean;
    }

具体过滤器的代码如下

public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURL().toString().matches(".+.ico$")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            String origin = request.getHeader("Origin");
	       // 简单请求跨域,如果是跨域请求在响应头里面添加对应的Origin
	        if (!StringUtils.isEmpty(origin)) {
	            response.addHeader("Access-Control-Allow-Origin", origin);
	        }
	        // 非简单请求跨域
	        response.addHeader("Access-Control-Allow-Headers", "content-type");
	        // 允许跨域请求的方法
	        response.addHeader("Access-Control-Allow-Methods", "*");
	        // 预检命令缓存 1小时
	//        response.addHeader("Access-Control-Max-Age", "3600");
	        // 携带cookie的跨域
	        response.addHeader("Access-Control-Allow-Credentials", "true");
	        // 放行方法
	        filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    @Override
    public void destroy() {
    }
}

你可能感兴趣的:(springboot过滤器执行两次的解决及跨域过滤器)