一,基础知识
拦截器,它是基于AOP来实现的,它拦截的对象一般是方法。你可以使用拦截器来对某些方法执行某些任务,例如在 Controller 处理请求之前编写日志,添加或更新配置......
二,实战
配置类:
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 作用所有方法
// registry.addInterceptor(new LogCostInterceptor());
// 作用于/admin/oldLogin
registry.addInterceptor(new LogCostInterceptor())
.addPathPatterns("/testFilter");
// 作用于/admin/* 但不包括/admin/oldLogin
// registry.addInterceptor(new LogCostInterceptor())
// .addPathPatterns("/admin/*")//
// .excludePathPatterns("/admin/oldLogin");
}
}
过滤器:打印方法执行时间
public class LogCostInterceptor implements HandlerInterceptor {
long start = System.currentTimeMillis();
/**
* 请求前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
start = System.currentTimeMillis();
return true;
}
/**
* 请求后执行(前提是preHandle返回true才执行)
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor cost="+(System.currentTimeMillis()-start));
}
/**
* 渲染视图后才执行(前提是preHandle返回true才执行)
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
}
测试: