How to modify request body before reaching controller in spring boot

BlueCloud :

I have a spring boot application. I change the request body of every post request. Is it possible to modify the request body before the request reaches the controller. Please include an example.

DwB :

Short Answer
Yes, but not easily.

Details
I know of three options to change the body of a request "before" it arrives at the handler method in the controller;

  1. Use AOP to change the request before the method is called.
  2. Create an HTTP filter.
  3. Create a custom Spring HandlerInterceptor.

Since you are already using spring-boot, option 3, custom Spring HandlerInterceptor, seems like the best option for you.

Here is a link to a Baeldung Article covering spring HandlerInterceptors.

The Baeldung article is not the full answer for your problem because you can only read the InputStrem returned by HttpServletRequest one time.

You will need to create a wrapper class that extends HttpServletRequest and wrap every request in your wrapper class within your custom HandlerInterceptor or in a custom Filter (Filter might be the way to go here).

Wrapper Class

  1. Read the HttpServletRequest InputStream in the wrapper class constructor
  2. Modify the body per your requirements.
  3. Write the modified body to a ByteArrayOutputStream.
  4. Use toByteArray to retrieve the actual byte[] from the stream.
  5. Close the ByteArrayOutputStream (try-with-resources is good for this).
  6. Override the getInputStream method.
  7. Wrap the byte[] in a ByteArrayInputStream every time the getInputStream is called. Return this stream.

How To Wrap the Request

  1. In your Filter, instantiate your wrapper class and pass in the original request (which is a parameter to the doFilter method).
  2. Pass the wrapper to the chain.doFilter method (not the original request).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441034&siteId=1