以springboot的拦截器实现原理为例

public class IpCountInterceptor implements HandlerInterceptor {

@Autowired
private IpCountService ipCountService;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ipCountService.count();
Exception e = new Exception("this is a log");
e.printStackTrace();
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}

  

实现了HandlerInterceptor接口,在容器接收到http请求的时候,会变量所有的拦截器是否有对应的实现类,如果有,则执行该实现类。达到实现了该接口就会被调用的目的。

调用的源代码如下:

boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex = i++) {
HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i);
if (!interceptor.preHandle(request, response, this.handler)) {
this.triggerAfterCompletion(request, response, (Exception)null);
return false;
}
}

return true;
}

  

暗夜之中,才见繁星;危机之下,暗藏转机;事在人为,为者常成。