Skip to content

ContentCachingRequestWrapper#getContentAsByteArray is empty before FilterChain#doFilter #28391

@brucelwl

Description

@brucelwl

ContentCachingRequestWrapper#getContentAsByteArray is empty before javax.servlet.FilterChain#doFilter

public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) servletRequest);
        ContentCachingResponseWrapper contentCachingResponseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);

        byte[] contentAsByteArray = contentCachingRequestWrapper.getContentAsByteArray();
        // but contentAsByteArray is empty
        String s = new String(contentAsByteArray);
        System.out.println("request body:" + s);

        chain.doFilter(contentCachingRequestWrapper, contentCachingResponseWrapper);

        byte[] contentAsBytes = contentCachingRequestWrapper.getContentAsByteArray();
        // contentAsBytes is not empty
        String str = new String(contentAsBytes);
        System.out.println("request body:" + str);

        byte[] contentAsByteArray1 = contentCachingResponseWrapper.getContentAsByteArray();
        String s1 = new String(contentAsByteArray1);
        System.out.println("response body:" + s1);
        
        contentCachingResponseWrapper.copyBodyToResponse();
    }
    
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    for: stackoverflowA question that's better suited to stackoverflow.comin: webIssues in web modules (web, webmvc, webflux, websocket)status: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions