Spring reading request body twice

后端 未结 3 419
花落未央
花落未央 2021-01-05 22:25

In spring I have a controller with an endpoint like so:

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
publ         


        
3条回答
  •  甜味超标
    2021-01-05 22:57

    To read the request body multiple times, we must cache the initial payload. Because once the original InputStream is consumed we can't read it again.

    Firstly, Spring MVC provides the ContentCachingRequestWrapper class which stores the original content. So we can retrieve the body multiple times calling the getContentAsByteArray() method.

    So in your case, you can make use of this class in a Filter:

    @Component
    public class CachingRequestBodyFilter extends GenericFilterBean {
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
      throws IOException, ServletException {
            HttpServletRequest currentRequest = (HttpServletRequest) servletRequest;
            ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(currentRequest);
            // Other details
    
            chain.doFilter(wrappedRequest, servletResponse);
        }
    }
    

    Alternatively, you can register CommonsRequestLoggingFilter in your application. This filter uses ContentCachingRequestWrapper behind the scenes and is designed for logging the requests.

提交回复
热议问题