0

I am implementing an interceptor for logging purposes. I know once i called the getReader method on HttpServletRequest will loose the body data, but i was experimenting. So i ran the below code, and realized the controller is never invoked (Debug point is not activated) and there was no errors.

@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);
    }

}

And the controller

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

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

        return "test";
    }

Filter Registration

@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Autowired
    IncomingRequestInterceptor incomingRequestInterceptor;

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

}

if i do not call getReader() method, the controller is invoked. I was actually expecting the controller is called but i would get a null pointer or something like that. Could anyone tell me how spring acts in this scenario ?

  • I think you need to register your interceptor https://stackoverflow.com/questions/31082981/spring-boot-adding-http-request-interceptors – Toerktumlare Jul 17 '19 at 18:27
  • And remember i spring 5 it is called WebMvcConfigurer and not WebMvcConfigurerAdapter – Toerktumlare Jul 17 '19 at 18:28
  • @ThomasAndolf Hello, i have already registered it, i have updated my question. The problem is preHandle is invoked, but not the controller. – teslacoil833 Jul 17 '19 at 18:31
  • Because the body is already consumed, there is no way to call the method and create a `CredentialsVo`. Basically there is nothing left to invoke the method with. – M. Deinum Jul 18 '19 at 05:20

0 Answers0