Spring reading request body twice

后端 未结 3 398
花落未央
花落未央 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:56

    As referenced in this post: How to Log HttpRequest and HttpResponse in a file?, spring provides the AbstractRequestLoggingFilter you can use to log the request.

    AbstractRequestLoggingFilter API Docs, found here

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 23:01

    I also tried to do that in Spring but i could not find way to pass my custom http request to chain so what did was,i have written traditional j2ee filter in that i have passed my custom http request to chain that is it then onward i can read http request more than once

    Check this example http://www.myjavarecipes.com/how-to-read-post-request-data-twice-in-spring/

    0 讨论(0)
提交回复
热议问题