1、定义一个filter接口
public interface Filter {
//接口方法
String doFilter(String data, FilterChain filterChain);
//过滤关键字的方法
default String filterByWord(String data, String word) {
StringBuilder sb = new StringBuilder(data);
while (true) {
int index = sb.indexOf(word);
if (index != -1) {
for (int i = 0; i < word.length(); i++) {
//关键字有几个字,就删几次。比如水果就在index删两次即可
sb.deleteCharAt(index);
}
} else {
//如果找不到关键字,就跳出循环
break;
}
}
return sb.toString();
}
}
2、过滤器实现类
public class FruitsFilter implements Filter {
@Override
public String doFilter(String data, FilterChain filterChain) {
//过滤水果关键字
data = filterByWord(data, "水果");
//拿到控制器,继续调用下一个过滤器
return filterChain.preHandleRequest(data);
}
}
public class VegetablesFilter implements Filter {
@Override
public String doFilter(String data, FilterChain filterChain) {
//过滤蔬菜关键字
data = filterByWord(data, "蔬菜");
//拿到控制器,继续调用下一个过滤器
return filterChain.preHandleRequest(data);
}
}
3、过滤器责任链控制器
public class FilterChain {
//使用List封装过滤器,List是有序的
private List<Filter> filters = new ArrayList<>();
//过滤器的下标,从0开始,每次调用preHandleRequest方法就+1
private int index = 0;
//添加过滤器
public void addFilter(Filter filter) {
filters.add(filter);
}
//调用过滤器的doFilter()方法,并把指针+1指向下一个过滤器
public String preHandleRequest(String data) {
//如果指针大于集合的size,则return,不再往下调用,相当于递归的终结条件
if (index == filters.size()) {
return data;
}
Filter filter = filters.get(index);
//下标指针+1
index++;
//精髓在这个this,把自己再当做参数传进去,实现了递归
return filter.doFilter(data, this);
}
}
4、Service
public class Main {
public static void main(String[] args) throws Exception {
//创建请求体
String data = "肉蛋葱鸡水果蔬菜千层饼雅俗共赏第五层的马老师";
Request request = new Request();
request.setData(data);
//创建FilterChain执行链
FilterChain filterChain = new FilterChain();
//添加过滤器
filterChain.addFilter(new FruitsFilter());
filterChain.addFilter(new VegetablesFilter());
//调用调用链的preHandleRequest方法
String s = filterChain.preHandleRequest(request.getData());
request.setData(s);
//打印结果,验证
System.out.println(request.getData());//下面是打印结果,结果正确
//肉蛋葱鸡千层饼雅俗共赏第五层的马老师
}
}