参数转发: 对@ResponseBody 响应数据的拦截加密(或其他处理)

一.使用场景-参数转发 1.springMVC 中使用注解@ResponseBody 响应接口返回数据; 2.大批量接口需要对请求参数做同个或相似处理,,比

一.使用场景-参数转发

1.springMVC 中使用注解@ResponseBody 响应接口返回数据;

2.大批量接口需要对请求参数做同个或相似处理,,比如对接收参数做解密之类;

二.实现

实现 ResponseBodyAdvice 接口,重写beforeBodyWrite函数;

三.demo

加密

@Component
@ControllerAdvice(basePackages = "xxx.controller")
public class EncryptResponseBody implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return returnType.getMethodAnnotation(ResponseBody.class) != null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        // 提取响应数据
        Map respdata = (Map) body;
        // Object 实际接口中响应返回的对象类型
        Object resp = (Object) respdata.get("Object");
        if (resp.getData() != null) {
            byte[] reqdata = null;
            ObjectMapper mapper = new ObjectMapper();
            try {
                String jsonData = mapper.writeValueAsString(resp.getData());
                reqdata = jsonData.getBytes("utf-8");
            }
            catch (JsonProcessingException | UnsupportedEncodingException e) {
                throw new IllegalStateException("json转换失败");
            }
            // TODO 处理数据 例:resp.setXXXX();
        }
        return (T) respdata;
    }
}