了解了一下责任链模式,简单的说下自己的理解吧:
责任链就是说待处理的数据在request的时候,先经过filter1的处理,再经过filter2的处理,然后response时,先经过filter2的处理,在经过filter1的处理。
实现思路是FilterChain包括filter1和filter2,同时,filter1和filter2同时都拥有FilterChain的引用,在FilterChain(fc)调用filter1之后,通过自身持有的fc再次调用fc的下一个filter。
那么在执行完最后一个filter之后,会返回到前一个filter。
public class FilterChain {
private List<Filter> filters = new ArrayList<Filter>();
int index = 0;
public void doFilter(Request request , Response response , FilterChain fc){
if(index == filters.size()){
return;
}
Filter f = filters.get(index);
index++;
f.doFileter(request, response,fc);
}
}
public interface Filter {
public void doFileter(Request request , Response response , FilterChain filterChain);
//实现类中,在执行完之后再次调用dofilter方法
/**public void doFileter(Request request, Response response ,FilterChain filterChain) {
request.requestStr = request.requestStr.replace("喵", "猫");
filterChain.doFilter(request, response, filterChain);//执行完第一步之后调用dofilter方法,继续调用下一个filter
response.responseStr += "111";
}
**/
}