Issue
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.
Solution
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;
- Use AOP to change the request before the method is called.
- Create an HTTP filter.
- 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
- Read the
HttpServletRequest
InputStream in the wrapper class constructor - Modify the body per your requirements.
- Write the modified body to a
ByteArrayOutputStream
. - Use
toByteArray
to retrieve the actualbyte[]
from the stream. - Close the ByteArrayOutputStream (try-with-resources is good for this).
- Override the
getInputStream
method. - Wrap the
byte[]
in a ByteArrayInputStream every time thegetInputStream
is called. Return this stream.
How To Wrap the Request
- In your Filter, instantiate your wrapper class and pass in the original request (which is a parameter to the doFilter method).
- Pass the wrapper to the chain.doFilter method (not the original request).
Answered By - DwB
Answer Checked By - Cary Denson (JavaFixing Admin)