Springboot 请求参数通知RequestBodyAdvice和响应通知ResponseBodyAdvice做日志的打印

1,请求参数的打印

@ControllerAdvice(basePackages = "控制器的命名空间")
public class LogRequestAdvice implements RequestBodyAdvice {
Logger logger = LoggerFactory.getLogger(getClass());

@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
//判断是否有此注解
boolean b = methodParameter.getParameterAnnotation(RequestBody.class) != null;
//只有为true时才会执行afterBodyRead
return b;
}

@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
InputStream body = httpInputMessage.getBody();
return new MappingJacksonInputMessage(httpInputMessage.getBody(), httpInputMessage.getHeaders());
}

@Override
public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
//仅仅打印请求参数
String s = JSON.toJSONString(o);
/**
* 去除注 回车 \n 水平制表符 \t 空格 \s 换行 \r
*/
String s2 = StringUtils.replaceBlankByLow(s);
logger.info("请求参数为:{}", s2);
return o;
}

@Override
public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return null;
}
2,请求参数的打印
@ControllerAdvice(basePackages = "控制器的命名空间")
public class LogResponseAdvice implements ResponseBodyAdvice<Object> {

Logger logger = LoggerFactory.getLogger(LogResponseAdvice.class);

@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
/**
* 仅仅打印返回的参数参数
*/
String s = JSON.toJSONString(body);
logger.info("返回值为:{}", s);
return body;
}


转载于:https://www.cnblogs.com/guagua-join-1/p/10368533.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值