在项目中看到使用@ControllerAdvice配合RequestBodyAdvice/ResponseBodyAdvice来拦截请求,对其中的数据进行加密,写法非常清晰有必要学习一下。
用法
controllerAdvice可以配合RequestBodyAdvice/ResponseBodyAdvice,在请求来时或请求走的时候拿到请求中的数据,对数据进行处理,在一定程度上可以替代interceptor.
//要扫描的包名
@ControllerAdvice(basePackages = "xxxx")
public class RequestBodyDecryptTokenAdvice extends RequestBodyAdviceAdapter {
//最先执行,判断是否支持使用
@Override
public boolean supports(MethodParameter arg0, Type arg1, Class<? extends HttpMessageConverter<?>> arg2) {
}
//在请求体中读出数据
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
}
}
使用场景
- 打印请求、响应日志
- 对参数解密、对响应加密
- 对请求传入的非法字符做过滤/检测
局限
- xxxAdvice必须被@ControllerAdvice注解标注了才会生效,起到拦截的效果
- 它只能作用于基于消息转换器的请求/响应(参考注解@RequestBody/@ResponseBody)
- 只能作用于@RequestMapping模式下的处理器模型上