实现基类
@Slf4jpublic abstract class BaseAnnotationInterceptor{ Class annotationClass; @SuppressWarnings("unchecked") @PostConstruct protected void PostConstruct() { annotationClass = (Class ) ReflectionUtils.getGenricType(this.getClass(), 0); if (log.isInfoEnabled()) { log.info("注解{},过滤器{}", annotationClass, this.getClass().getName()); } } public Class getAnnotationClass() { return annotationClass; } public abstract boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, T annotation); public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView, T annotation) { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, Exception ex, T annotation) { }}
这里的方法名与spring中HandlerInterceptorAdapter对应
过滤器实现
@Component@SuppressWarnings({ "rawtypes", "unchecked" })@Slf4jpublic class WebRequestInterceptor extends HandlerInterceptorAdapter { @Autowired(required = false) Listinterceptors; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod) || interceptors == null) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; for (Map.Entry entry : getAnnotations(handlerMethod).entrySet()) { if (!entry.getValue().preHandle(request, response, handlerMethod, entry.getKey())) { if (log.isDebugEnabled()) { log.debug("请求{}被拦截,class={}", request.getRequestURI(), entry.getValue().getClass().getName()); } return false; } } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (!(handler instanceof HandlerMethod) || interceptors == null) { return; } HandlerMethod handlerMethod = (HandlerMethod) handler; for (Map.Entry entry : getAnnotations(handlerMethod).entrySet()) { entry.getValue().postHandle(request, response, handlerMethod, modelAndView, entry.getKey()); } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if (!(handler instanceof HandlerMethod) || interceptors == null) { return; } HandlerMethod handlerMethod = (HandlerMethod) handler; for (Map.Entry entry : getAnnotations(handlerMethod).entrySet()) { entry.getValue().afterCompletion(request, response, handlerMethod, ex, entry.getKey()); } } private Map getAnnotations(HandlerMethod handlerMethod) { Map map = new HashMap<>(); Map , Annotation> annotationMap = AnnotationUtil.getAnnotations(handlerMethod); for (BaseAnnotationInterceptor interceptor : interceptors) { Annotation annotation = annotationMap.get(interceptor.getAnnotationClass()); if (annotation != null) { map.put(annotation, interceptor); } } return map; }}
registry.addInterceptor(webRequestInterceptor).addPathPatterns("/**");配置过滤器