Logic I have to implement is logging all requests with body served to DB.
So I decided to use: afterCompletion
method of HandlerInterceptor
.
There are two parameters passed to this method HttpServletRequest
and HttpServletResponse
among the others.
Question is: how to get RequestBody
and ResponseBody
from supplied objects?
As far as I know at Controller we can use @RequestBody
and @ResponseBody
. Can I reuse them at HandlerInterceptor
?
In this article, we will discuss how to get the body of the incoming request in the spring boot. @RequestBody: Annotation is used to get request body in the incoming request. Note: First we need to establish the spring application in our project. Step 2: Click on Generate which will download the starter project.
By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.
If you don't add @RequestBody it will insert null values (should use), no need to use @ResponseBody since it's part of @RestController.
The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
You can extend RequestBodyAdviceAdapter
and implement the method afterBodyRead
:
@ControllerAdvice
public MyRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
// write body -your input dto- to logs or database or whatever
return body;
}
}
The RequestBodyAdvice comes in pre setp the request chain before the HandlerInterceptor
. it is exactly after the http request inputstream is converted to your object.
As far as I know, RequestBody
and ResponseBody
can be read only once. So you should not read them in an Interceptor
.
Here's some explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With