Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get RequestBody and ResponseBody at HandlerInterceptor

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?

like image 255
kyberorg Avatar asked Jan 17 '14 18:01

kyberorg


People also ask

Can we use @RequestBody with get in Spring boot?

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.

What is @RequestBody and @ResponseBody?

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.

Is @RequestBody required with @RestController?

If you don't add @RequestBody it will insert null values (should use), no need to use @ResponseBody since it's part of @RestController.

What is the purpose of the ResponseBody annotation?

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.


2 Answers

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.

like image 72
Muhammad Hewedy Avatar answered Sep 17 '22 06:09

Muhammad Hewedy


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.

like image 36
marcellsimon Avatar answered Sep 18 '22 06:09

marcellsimon