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;
}
java 返回参数加密
最新推荐文章于 2024-09-08 10:40:56 发布