开发过程中并不是所有接口都要验证登录的,对于不需要验证登录的控制器或方法需要定义一种能跳过拦截器的注解。
@Target(value = {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Uncontrol {
}
接着在拦截器的preHandle方法内,在验证登录的逻辑处理前添加如下代码
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Uncontrol uncontrolAnnotation = handlerMethod.getMethodAnnotation(Uncontrol.class);
if (Objects.nonNull(uncontrolAnnotation)) {
System.out.println("Method @Uncontrol");
return true;
}
Class<?> clazz = handlerMethod.getBeanType();
if (Objects.nonNull(AnnotationUtils.findAnnotation(clazz, Uncontrol.class))) {
System.out.println("Class @Uncontrol");
return true;
}
}
logger.info("验证用户登录情况");
//验证用户登录的逻辑部分
return true;
}
然后给不需要拦截的方法或类加上@Uncontrol
注解,拦截器就会放行此方法或类
加在方法上是不拦截此方法,加在类上是不拦截此类中所有方法,方法的注解优先。