Home > database >  Interceptor PreHandle ContentCachingRequestWrapper request Empty
Interceptor PreHandle ContentCachingRequestWrapper request Empty

Time:07-07

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());
        }
}

CodePudding user response:

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);
  • Related