9.Interceptor拦截器

也考虑使用系统自带的拦截器Servlets, Filters, listeners

实现HandlerInterceptor 接口,比如如下示例:当rest调用时,打印时间。其中afterCompletion 当正确调用后或者异常情况下都会被调用。而postHandle只会在正确调用后执行。

@Component
public class TimeInterceptor implements HandlerInterceptor {

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        System.out.println("这里是preHandle");
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());

        request.setAttribute("startTime", new Date().getTime());

        MDC.put("userId", "123456");

        return true;
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

        System.out.println("这里是postHandle");
        System.out.println("服务处理耗时:"+(new Date().getTime() - (Long)request.getAttribute("startTime"))+"毫秒");

    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        System.out.println("这里是afterCompletion");
        System.out.println("服务处理耗时:"+(new Date().getTime() - (Long)request.getAttribute("startTime"))+"毫秒");
        System.out.println("ex is "+ ex);
    }

}

还需要进行配置,创建配置类

public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private TimeInterceptor timeInterceptor;

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

Last updated