有这么一个需求,在request和response过来的时候,我们有多个filter,需要先request经过filter1,再request经过filter2,然后response经过filter1,最后response经过filter2。
如图:
直接上代码
public class Main {
public static void main(String[] args) {
MyRequest request = new MyRequest();
request.str = "aaa111aaa";
MyResponse response = new MyResponse();
response.str = "bbb222bbb";
MyFilterChain myFilterChain = new MyFilterChain();
myFilterChain.add(new HTMLFilter());
myFilterChain.add(new SenFilter());
myFilterChain.doFilter(request, response);
}
}
interface MyFilter {
void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain);
}
class MyRequest {
String str;
}
class MyResponse {
String str;
}
class HTMLFilter implements MyFilter {
@Override
public void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain) {
System.out.println("do HTMLFilter req");
request.str.replace("111", "...");
filterChain.doFilter(request, response);
System.out.println("do HTMLFilter resp");
}
}
class SenFilter implements MyFilter {
@Override
public void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain) {
System.out.println("do SenFilter req");
request.str.replace("222", "!!!");
filterChain.doFilter(request, response);
System.out.println("do SenFilter resp");
}
}
class MyFilterChain {
List<MyFilter> filters = new ArrayList<>();
int index = 0;
public void doFilter(MyRequest request, MyResponse response) {
if (filters.size() > index) {
filters.get(index++).doFilter(request, response, this);
}
}
public MyFilterChain add(MyFilter filter) {
filters.add(filter);
return this;
}
}