首页 > 编程学习 > 对于接口是在java里面的应用场景

对于接口是在java里面的应用场景

发布时间:2022/9/9 17:48:16

以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;
    }

  

Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号