赞
踩
@ControllerAdvice 这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:
这里主要介绍一下 第3点 全局数据预处理,运用场景为全局打印请求参数和请求路径,
@ControllerAdvice
public class MyRequestControllerAdvice implements RequestBodyAdviceAdapter {
private Logger logger = LoggerFactory.getLogger(MyRequestControllerAdvice .class):
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return true; // 代表所有方法都进入
// return methodParameter.hasParameterAnnotation(RequestBody.class);
}
@Autowired
private MySecretUtil mySecretUtil;
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
String bodyStr = IOUtils.toString(httpInputMessage.getBody());
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
// 打印日志
logger.info(new StringBulder("请求路径:").append(request .getRequestURI()).append(",,,,参数:").append(bodyStr ));
if (methodParameter.getMethod().isAnnotationPresent(SecretAnnotation.class)) {
SecretAnnotation secretAnnotation = methodParameter.getMethod().getAnnotation(SecretAnnotation.class);
if (secretAnnotation.decode()) {
return new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
List<String> appIdList = httpInputMessage.getHeaders().get("appId");
if (appIdList.isEmpty()){
throw new RuntimeException("请求头缺少appID");
}
String appId = appIdList.get(0);
String bodyStr = IOUtils.toString(httpInputMessage.getBody(),"utf-8");
bodyStr = mySecretUtil.decode(bodyStr,appId);
return IOUtils.toInputStream(bodyStr,"utf-8");
}
@Override
public HttpHeaders getHeaders() {
return httpInputMessage.getHeaders();
}
};
}
}
return httpInputMessage;
}
}
————————————————
版权声明:本文为CSDN博主「more_try」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/more_try/article/details/88682588
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。