Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...