初始化请看RequestMappingHandlerAdapter的初始化原理
@ControllerAdvice
public class LuckBodyAdvice implements RequestBodyAdvice, ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
// 对请求体进行处理,可以在这个进行加密解密
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
InputStream body = inputMessage.getBody();
String read = IoUtil.read(body, Charset.defaultCharset());
Object object = JSON.parseObject(read, targetType);
if (object instanceof A) {
A a = (A) object;
a.setId(-1);
}
return new MappingJacksonInputMessage(new ByteArrayInputStream(JSON.toJSONString(object).getBytes(StandardCharsets.UTF_8)), inputMessage.getHeaders());
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
// 响应之前对结果进行处理,可以做统一响应结果集
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
return body;
}
}
RequestBodyAdvice请求数据处理和ResponseBodyAdvice响应数据处理
最新推荐文章于 2024-04-04 08:00:43 发布