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

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

转自:https://lingkang.top/archives/java-guo-lv-qi-yuan-li-bing-shi-xian-yi-ge-guo-lv-qi

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

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值