Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...