简体   繁体   中英

How to log RequestBody in async spring controller?

I added an async endpoint to a existing spring-mvc application:

@RestController
public class MyController {
    @PostMapping("/")
    public Mono<String> post(Object body) {
       return Mono.just("test");
       //webClient.retrieve().bodyToMono(String.class);
    }
}

I want to create a global interceptor/filter that will log the request body payload. But how can I get access to it?

I tried adding a HandlerInterceptorAdapter , but the payload is always empty:

static class LoggingInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
            byte[] buf = wrapper.getContentAsByteArray();
            System.out.println(buf);
            System.out.println(buf.length);

            return true;
        }
}

Maybe the payload is not yet present in the request, or has already been read. So how can I access the body in this async case?

Unfortunately in Webflux you cannot use HandlerInterceptorAdapter because it came from web mvc module and works only with the servlets. I found a good article with solutions .

PS You must to remove spring-mvc dependencies if going to use reactive endpoins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM