注意:如果请求返回为对象可考虑用ibatis拦截器加参数注解实现
1.定义:请求参数注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SM4MethodParam {
//参数列表下标 0开始, 不传默认加密第一个参数
int[] value() default {};
}
2.定义:返回参数注解
//标记为返回参数要加密
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={METHOD})
public @interface SM4MethodReturn {
}
3.定义情面类
package com.rtzh.ejjzhgd.common.aop.sm4; import com.rtzh.ejjzhgd.common.annotation.SM4MethodParam; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.util.List; import static com.rtzh.ejjzhgd.common.interceptor.utils.EncryptDecryptUtils.decryptField; import static com.rtzh.ejjzhgd.common.interceptor.utils.EncryptDecryptUtils.encryptField; @Slf4j @Aspect @Component public class SM4ReturnPoint { @Pointcut("@annotation(com.rtzh.ejjzhgd.common.annotation.SM4MethodParam)") public void preProcess() { } //修改请求参数 @Around("preProcess()") public Object sm4QueryParam(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); SM4MethodParam annotation = signature.getMethod().getAnnotation(SM4MethodParam.class); Object[] args = joinPoint.getArgs(); // 从annotation中获取参数 int[] value = annotation.value(); if(null != value && value.length > 0){ for (int index :value){ args[index] = encryptField(args[index].toString()); } }else { args[0] = encryptField(args[0].toString()); } return joinPoint.proceed(args); } //修改返回值 @Around("@annotation(com.rtzh.ejjzhgd.common.annotation.SM4MethodReturn)") public Object sm4MethodReturn(ProceedingJoinPoint joinPoint) throws Throwable { Object returnValue = joinPoint.proceed(); if(returnValue instanceof String){ returnValue = decryptField(returnValue.toString()); }else if(returnValue instanceof List){ for (Object o : (List)returnValue){ if(o instanceof String){ o = decryptField(o.toString()); } } } return returnValue; } }
4.用法示例
@Select("select emergency_phone from rt_project_person where emergency_phone = #{emergencyPhone} and emergency_contact = #{emergencyContact}")
@SM4MethodReturn
@SM4MethodParam({0,1})
List<String> selectLists( @Param("emergencyPhone") String emergencyPhone, @Param("emergencyContact") String emergencyContact);