Http Servlet request lose params from POST body after read it once

前端 未结 13 2112
一个人的身影
一个人的身影 2020-11-22 14:56

I\'m trying to accessing two http request parameters in a Java Servlet filter, nothing new here, but was surprised to find that the parameters have already been consumed! Be

13条回答
  •  抹茶落季
    2020-11-22 15:39

    I know I'm late, but this question was still relevant for me and this SO post was one of the top hits in Google. I'm going ahead and post my solution in the hopes that someone else might save couple of hours.

    In my case I needed to log all requests and responses with their bodies. Using Spring Framework the answer is actually quite simple, just use ContentCachingRequestWrapper and ContentCachingResponseWrapper.

    import org.springframework.web.util.ContentCachingRequestWrapper;
    import org.springframework.web.util.ContentCachingResponseWrapper;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class LoggingFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void destroy() {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    
            ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
            ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
    
            try {
                chain.doFilter(requestWrapper, responseWrapper);
            } finally {
    
                String requestBody = new String(requestWrapper.getContentAsByteArray());
                String responseBody = new String(responseWrapper.getContentAsByteArray());
                // Do not forget this line after reading response content or actual response will be empty!
                responseWrapper.copyBodyToResponse();
    
                // Write request and response body, headers, timestamps etc. to log files
    
            }
    
        }
    
    }
    

提交回复
热议问题