java过滤器原理并实现一个过滤器

web中的过滤器,将所有请求进行拦截过滤,并能够再过滤前处理和过滤后处理。
下面我手动实现一个过滤器,使用到了递归的思路:

1、先定义一个过滤器接口,很标准,没的说。

/**
 * @author lingkang
 * Created by 2022/12/7
 */
public interface Filter {
    void doFilter(Object req,Object res,FilterChain filterChain)throws Exception;
}

2、编写一个过滤连作为递归操作

/**
 * @author lingkang
 * Created by 2022/12/7
 */
public class FilterChain {
    public Filter[] filters;
    public int length = 0, current = 0;

    public FilterChain(Filter[] filters) {
        this.filters = filters;
        length = filters.length;
    }

    void doFilter(Object req, Object res) throws Exception {
        if (current < length) {
            current++;// 自增
            filters[current - 1].doFilter(req, res, this);
        } else {
            current=0;//reset
            // 在此处调用处理逻辑方法
            System.out.println("finish");
        }
    }
}

3、执行过滤器

/**
 * @author lingkang
 * Created by 2022/12/7
 * 过滤器实现原理,递归实现
 */
public class Main {

    public static void main(String[] args) throws Exception {
        Filter[] filters = new Filter[2];// 自定义过滤
        filters[0] = new F1();
        filters[1] = new F2();
        FilterChain filterChain = new FilterChain(filters);

        Object req = null, res = null;
        filterChain.doFilter(req, res);// 模拟过滤

        System.out.println("OK");
    }

    static class F1 implements Filter {
        @Override
        public void doFilter(Object req, Object res, FilterChain filterChain) throws Exception {
            System.out.println("F1 前");
            filterChain.doFilter(req, res);
            System.out.println("F1 后");
        }
    }

    static class F2 implements Filter {
        @Override
        public void doFilter(Object req, Object res, FilterChain filterChain) throws Exception {
            System.out.println("F2 前");
            filterChain.doFilter(req, res);
            System.out.println("F2 后");
        }
    }
}

效果输出如下:

F1 前
F2 前
finish
F2 后
F1 后
OK

image-1670407413520