为什么拦截器会运行三遍?

时间:2018-11-17 08:54:50

标签: java spring-mvc spring-boot

 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
    String jwt = request.getHeader("auth");
    String payloadKey = "apitest";
    HandlerMethod handlerMethod=(HandlerMethod)object;
    Class type = handlerMethod.getBeanType();
    if (type.isAnnotationPresent(Auth.class)) {
        try {
            if (jwt == null || !Objects.equals(payloadKey, JwtUtil.parseJWT(jwt).get("info", String.class))) {
                return false;
            }
        }catch (ExpiredJwtException | SignatureException | MalformedJwtException e){
            return false;
        }
    }
    log.info("1");
    return true;
}

当jwt是true时,但我看到log.info(“ 1”)运行3次,为什么它运行3次?

我的拦截器配置:

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authenticationInterceptor())
            .addPathPatterns("/**");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
    return new AuthenticationInterceptor();
}

我在控制器类上设置了@Auth: @Auth公共类ApiController

当我清除preHandle时,排除运行3次的“ log.info(“ 1”)返回true”

1 个答案:

答案 0 :(得分:0)

已更新

您可以调试到AuthenticationInterceptor中,以确认某些内容:

  1. 如果handlerMethod总共指向3个不同的对象?

  2. AuthenticationInterceptor变量的this是否不同?

  3. 如果您的请求有一些重定向?

我尝试使用类似您的代码,它具有正确的行为。您可以显示更多代码还是重现问题的简单方法?

相关问题