Get RequestBody and ResponseBody at HandlerInterceptor

前端 未结 7 1796
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 11:31

Logic I have to implement is logging all requests with body served to DB.

So I decided to use: afterCompletion method of HandlerInterceptor

7条回答
  •  庸人自扰
    2020-12-14 12:11

    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> 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.

提交回复
热议问题