欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(三)、SpringBoot 自定义 interceptor(拦截器)

程序员文章站 2022-07-09 22:41:03
...

可以前往第一篇博客查看目录结构 --> 这里

一、创建interceptor包

(三)、SpringBoot 自定义 interceptor(拦截器)

二、在interceptor包下创建TimeInterceptor类,自定义Interceptor

@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("interceptor preHandle");
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        request.setAttribute("start",new Date().getTime());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("interceptor postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("interceptor afterCompletion");
        long start = (long) request.getAttribute("start");
        System.out.println("interceptor耗时: " + (new Date().getTime() - start));
    }
}

三、在config包下的WebConfig类下添加下述代码,配置自定义的TimeInterceptor进入

    @Autowired
    private TimeInterceptor timeInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }

四、访问 localhost/user ,查看IDEA控制台即可