0

I want to use this interceptor to log the requests and responses into database. I tried this code:

public class LoggerInterceptor extends HandlerInterceptorAdapter {

    private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);

    /**
     * Executed before actual handler is executed
     **/
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() );

        String test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        System.out.println("~~~~~~~~ request " + test);
        return true;
    }

    /**
     * Executed before after handler is executed
     **/
    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
        log.info("[postHandle][" + request + "]");
        System.out.println("~~~~~~~~ response ");
    }

    /**
     * Executed after complete request is finished
     **/
    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
        if (ex != null)
            ex.printStackTrace();
        log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
    }    
}

But I get NULL. What is the proper way to implement this?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • You get `NULL` where? – Andreas May 22 '19 at 21:38
  • at this line `System.out.println("~~~~~~~~ request " + test);` – Peter Penzov May 22 '19 at 21:50
  • 1
    `test` cannot be `null`. Or are you saying the content of the request's `Reader` is literally the text content `NULL`? Please provide a [mcve]. – Sotirios Delimanolis May 22 '19 at 22:31
  • 1
    You cannot do this in an interceptor, you need to do this in a `Filter` and wrap the incoming request. You can only read the payload once. If you read it here in the interceptor, your controllers will break. Spring already [has special logigng filters](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/filter/CommonsRequestLoggingFilter.html) for this, use those instead. – M. Deinum May 23 '19 at 05:45

0 Answers0