Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interceptor PreHandle ContentCachingRequestWrapper request Empty

Request from Interceptor preHandle is empty. Why is this happening?

@Component
public class CustomServletWrappingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        ContentCachingRequestWrapper wrappingRequest = new ContentCachingRequestWrapper(httpServletRequest);
        ContentCachingResponseWrapper wrappingResponse = new ContentCachingResponseWrapper(httpServletResponse);
        filterChain.doFilter(wrappingRequest, wrappingResponse);
        wrappingResponse.copyBodyToResponse();
    }

}

preHandle request is Empty

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (CallCountUtil.isMimeTypeJson(request)) {
            ContentCachingRequestWrapper cachingRequestWrapper = (ContentCachingRequestWrapper) request;
            String json = new String(cachingRequestWrapper.getContentAsByteArray());
        }
}

afterCompletion request is ok.

@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws IOException {
        if (CallCountUtil.isMimeTypeJson(request)) {
            ContentCachingRequestWrapper cachingRequestWrapper = (ContentCachingRequestWrapper) request;
            String json = new String(cachingRequestWrapper.getContentAsByteArray());
        }
}
like image 917
Unknown_HHM Avatar asked Dec 17 '25 05:12

Unknown_HHM


1 Answers

If you read the javadocs you would have the answer.

This class acts as an interceptor that only caches content as it is being read but otherwise does not cause content to be read. That means if the request content is not consumed, then the content is not cached, and cannot be retrieved via getContentAsByteArray().

In the preHandle method the request hasn't been consumed yet and thus getContentAsByteArray() is empty. In the afterCompletion the request has been consumed and the cache has been filled and thus getContentAsByteArray() does return a value.

Basically you shouldn't care if it is a ContentCachingRequestWrapper, just read the InputStream from the HttpServletRequest as you normally would do.

Something like this.

String json = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
like image 131
M. Deinum Avatar answered Dec 20 '25 01:12

M. Deinum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!