对于接口是在java里面的应用场景
原创
©著作权归作者所有:来自51CTO博客作者wx5eba5c8cb0b6f的原创作品,请联系作者获取转载授权,否则将追究法律责任
以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;
}
暗夜之中,才见繁星;危机之下,暗藏转机;事在人为,为者常成。