这种一般都是通过实现RequestBodyAdvice
[Java] 纯文本查看 复制代码 @ControllerAdvice(assignableTypes={AnalyzeController.class})
public class RequestLogger implements RequestBodyAdvice, ResponseBodyAdvice<MyRequest> {
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
return httpInputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParzameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
MDC.put("key1","value1");
MDC.put("key2","value2");
MyRequestContextHolder.setContext(new MyRequest());
RequestContextHolder.getRequestAttributes().setAttribute("",body, RequestAttributes.SCOPE_REQUEST);
return body;
}
@Override
public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return o;
}
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public MyRequest beforeBodyWrite(MyRequest o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
MDC.clear();
MyRequestContextHolder.remove();
return o;
}
} |