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

一.使用场景-参数转发

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;
    }
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部