3

I need to fetch the entire request body in filter and convert it into String. Below is my code but nothing is getting printed on console.

@Component
public class WebFilter01 implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, 
      WebFilterChain webFilterChain) {    

        Flux<DataBuffer> requestBody = serverWebExchange.getRequest().getBody();        

        Flux<String> decodedRequest = requestBody.map(databuffer -> {
            return decodeDataBuffer(databuffer);
        });     
        decodedRequest.doOnNext(s -> System.out.print(s));
        return webFilterChain.filter(serverWebExchange);
    }


    protected String decodeDataBuffer(DataBuffer dataBuffer) {
        Charset charset = StandardCharsets.UTF_8;       
        CharBuffer charBuffer = charset.decode(dataBuffer.asByteBuffer());      
        DataBufferUtils.release(dataBuffer);        
        String value = charBuffer.toString();
        return value;
    }
}
mayank jain
  • 51
  • 1
  • 5

1 Answers1

2

Nothing is getting printed on console because you did not subscribe to decodedRequest , as we know one of the Reactive aspect:

Nothing happens until you subscribe

But if you do that you will see printed body on console but your code will not work, because the next operators cannot read the body and you will get IllegalStateException(Only one connection receive subscriber allowed.)

So, how to resolve it?

  1. Create your own wrapper for ServerWebExchange (please read about this here: How to log request and response bodies in Spring WebFlux)
  2. Log bodies in HttpMessageDecoder. If you see, for instance, AbstractJackson2Decoder you will found code where Spring decode you buffer to object and can log it:
try {
    Object value = reader.readValue(tokenBuffer.asParser(getObjectMapper()));
    if (!Hints.isLoggingSuppressed(hints)) {
        LogFormatUtils.traceDebug(logger, traceOn -> {
            String formatted = LogFormatUtils.formatValue(value, !traceOn);
            return Hints.getLogPrefix(hints) + "Decoded [" + formatted + "]";
        });
    }
    return value;
}
andred
  • 1,204
  • 1
  • 17
  • 29
Yauhen Balykin
  • 731
  • 5
  • 13