@ControllerAdvice
public class MyEncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
private boolean encrypt;//业务参数
@Autowired
private SecretKeyConfig secretKeyConfig;//业务参数
private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal();//业务参数
public MyEncryptResponseBodyAdvice() {
}
//返回true时才会执行beforeBodyWrite方法
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
this.encrypt = false;
if (returnType.getMethod().isAnnotationPresent(MyEncrypt.class) && !this.secretKeyConfig.isDebug()) {
this.encrypt = true;
}
return this.encrypt;
}
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
Boolean status = (Boolean)encryptLocal.get();
if (null != status && !status) {
encryptLocal.remove();
return body;
} else {
if (this.encrypt) {
String publicKey = this.secretKeyConfig.getPublicKey();
try {
String content = JSON.toJSONString(body);
if (!StringUtils.hasText(publicKey)) {
throw new NullPointerException("Please configure rsa.encrypt.privatekeyc parameter!");
}
String encodedData = AesUtil.aesEncrypt(content, publicKey);
//String result = new String(Base64.encodeBase64(encodedData));
return encodedData;
} catch (Exception var13) {
var13.printStackTrace();
}
}
return body;
}
}
}
java拦截接口返回参数ResponseBodyAdvice
最新推荐文章于 2024-06-13 11:26:38 发布