回调(个人理解):类A中任意方法中调用了类B的方法,而B方法又调用了A中某回调方法;
加了接口的说法:回调接口的实现类A里调用了B的方法,而B的方法里又调用了回调接口的回调方法,具体执行方法已经由实现类A重写(加接口是为了不把代码写死,方便复用)
现实场景下:A约B一起吃饭,B有事要做,等B事情做完,让B通知一下A(回调方法就是去吃饭)
回调推荐https://blog.csdn.net/lemon_tree12138/article/details/51231841
过滤器:推荐文章https://blog.csdn.net/beliefer/article/details/51894747
FilterChain是回调接口,doFilter(request,response)是回调方法,ApplicationFilterChain是实现类,里面能得到实现了Filter接口的实现类xxxFilter(平常我们自己写过滤器就是实现Filte接口并重写doFilter),在doFilter(request,response)中执行中了某个Filter实现类的doFilter(request, response, this)(this指的当前ApplicationFilterChain类)方法,在这个方法执行某些处理后需要回调ApplicationFilterChain.doFilter(request,response),这个回调会执行filter链中的下一个循环到结束
public interface FilterChain {
public void doFilter(ServletRequest request, ServletResponse response);
}
public final class ApplicationFilterChain implements FilterChain {
@Override
public void doFilter(ServletRequest request, ServletResponse response) {
...//省略
internalDoFilter(request,response);
}
private void internalDoFilter(ServletRequest request, ServletResponse response){
if (pos < n) {
//获取第pos个filter
ApplicationFilterConfig filterConfig = filters[pos++];
Filter filter = filterConfig.getFilter();
...
filter.doFilter(request, response, this);
}
}
}
public class xxFilter implements Filter{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain){
...
filterChain.doFilter(request, response);
}
}
因为ApplicationFilterChain是在回调方法里调用的各个filter的doFilter方法,而各个filter里又回调了ApplicationFilterChain的回调方法,所以会循环执行;有些文章是把Filter当回调接口,ApplicationFilterChain调用xxFilter的doFilter()当回调,理论上应该不算错(存疑),但实际场景是先执行ApplicationFilterChain,所以以此为主方法
————————————————
版权声明:本文为CSDN博主「默言yy」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011418473/article/details/79897383
网友评论