java 返回参数加密

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.huaze.common.util.SM4Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@Component
@ControllerAdvice
@Slf4j
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<Object> {



    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        //方法请求地址
        String methodUrl = null;
        if(ObjectUtil.isNotEmpty(returnType.getMethodAnnotation(RequestMapping.class))){
            methodUrl = returnType.getMethodAnnotation(RequestMapping.class).value()[0];
            if(methodUrl.startsWith("/")){
                methodUrl = methodUrl.replaceFirst("/","");
            }
        }
        //类请求地址
        String classUrl = null;
        if(ObjectUtil.isNotEmpty(returnType.getContainingClass().getAnnotation(RequestMapping.class))){
            classUrl = returnType.getContainingClass().getAnnotation(RequestMapping.class).value()[0];
            if(classUrl.startsWith("/")){
                classUrl = classUrl.replaceFirst("/","");
            }
        }
        if("test/connect".equals(classUrl+"/"+methodUrl)){
            return body;
        }
        //加密
        log.info("【接受到的数据】encode={}",body);
        if(!isJSON2(body)){
            return body;
        }
        return SM4Utils.encrypt( JSON.toJSONStringWithDateFormat(body
                , "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
    }
    public static boolean isJSON2(Object str) {
        boolean result = false;
        try {
            Object obj = JSONUtil.parseObj(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值