Use cached’s wrapper class to read the request response content

  springboot

Problem

Once the stream of servlet’s requestbody and response’s body is read, they cannot be consumed again, so this brings a potential pit for intercepting requests and recording relevant information. So how to deal with this, use filter, wrapper layer, then proceed, and finally set cached’s body back to the original response after the response is finished.

caching wrapper

ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);

Spring provides two classes, ContentCachingRequestWrapper and ContentCachingResponseWrapper, to solve such problems.
After reading body

wrappedResponse.copyBodyToResponse();

Through this setting back, the end consumer can receive the response normally.