为什么在preHandle中调用request.getReader后没有调用Spring Boot控制器

时间:2019-07-17 17:45:27

标签: spring spring-boot interceptor

我正在实现用于日志记录的拦截器。我知道一旦我在HttpServletRequest上调用getReader方法将丢失主体数据,但是我正在尝试。因此,我运行了以下代码,并意识到从未调用过控制器(未激活调试点)并且没有错误。

@Component
public class IncomingRequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String requestPayload = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        System.out.println(requestPayload);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        super.afterCompletion(request, response, handler, ex);
    }

}

还有控制器

    @PostMapping("/test")
    public String test(@Valid @RequestBody CredentialsVo credentials) {

        credentials.getUsername();
        .............

        return "test";
    }

过滤器注册

@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Autowired
    IncomingRequestInterceptor incomingRequestInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(incomingRequestInterceptor)
              .addPathPatterns("/**");
    }

}

如果我不调用getReader()方法,则调用控制器。我实际上期望控制器被调用,但是我会得到一个空指针或类似的东西。 谁能告诉我在这种情况下弹簧的作用?

0 个答案:

没有答案