SpringBoot中多种Filter配置方式

通过配置类方式,利用FilterRegistrationBean注册自定义的Filter过滤器

@Configuration
public class ComponentFilterOrderConfig {
	@Bean
	public Filter MyTestFilter(){
		return new MyTestFilter();//自定义的过滤器
	}
	
	@Bean
	public FilterRegistrationBean filterRegistrationBean(){
		FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
		filterRegistrationBean.setFilter(MyTestFilter());
		filterRegistrationBean.addUrlPatterns("/app/approval/*");
		filterRegistrationBean.setOrder(6);//order的数值越小 则优先级越高
		return filterRegistrationBean;
	}
}

实现Filter的方式

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)//控制过滤器的级别
public class CosFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws
            IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", reqs.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type,X-Requested-With");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }
}

用@WebFilter配置

@WebFilter(urlPatterns = "/*")
@Order(value = 1)
public class TestFilter implements Filter {
 
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/main/excludefilter", "/login", "/logout", "/register")));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init-----------filter");
    }
 
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
 
        if (allowedPath) {
            System.out.println("这里是不需要处理的url进入的方法");
            chain.doFilter(req, res);
        }
        else {
            System.out.println("这里是需要处理的url进入的方法");
        }
    }
 
    @Override
    public void destroy() {
        System.out.println("destroy----------filter");
    }
}
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页