1.springMVC 中使用注解@RequestBody 接收接口参数;
2.大批量接口需要对请求参数做同个或相似处理,,比如对接收参数做解密之类;
实现 RequestBodyAdvice 接口,重写beforeBodyRead函数;
@Component
@ControllerAdvice(basePackages = "demo.controller")//controller所在包
public class DemoRequestBody implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class extends HttpMessageConverter>> converterType) {
return true;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class extends HttpMessageConverter>> converterType) {
return body;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class extends HttpMessageConverter>> converterType)
throws IOException {
// 提取数据
InputStream is = inputMessage.getBody();
byte[] data = new byte[is.available()];
is.read(data);
//转数据类型
ObjectMapper mapper = new ObjectMapper();
Map
// 解密 / 其他数据处理
byte[] respData = // TODO;
// 回传处理后的数据
return new DecodedHttpInputMessage(inputMessage.getHeaders(), new ByteArrayInputStream(respData));
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class extends HttpMessageConverter>> converterType) {
return body;
}
static class DecodedHttpInputMessage implements HttpInputMessage {
HttpHeaders headers;
InputStream body;
public DecodedHttpInputMessage(HttpHeaders headers, InputStream body) {
this.headers = headers;
this.body = body;
}
@Override
public InputStream getBody() throws IOException {
return body;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
}
}