/**
- 定义有一个切入点,范围为web包下的类
*/
@Pointcut(“execution(public * com.bsapple.vshop.controller….(…))”)
public void checkParam() {
}
@Before(“checkParam()”)
public void doBefore(JoinPoint joinPoint) {
}
/**
- 检查参数是否为空
*/
@Around(“checkParam()”)
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature signature = ((MethodSignature) pjp.getSignature());
//得到拦截的方法
Method method = signature.getMethod();
//获取方法参数注解,返回二维数组是因为某些参数可能存在多个注解
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
if (parameterAnnotations == null || parameterAnnotations.length == 0) {
return pjp.proceed();
}
//获取方法参数名
String[] paramNames = signature.getParameterNames();
//获取参数值
Object[] paranValues = pjp.getArgs();
//获取方法参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterAnnotations.length; i++) {
for (int j = 0; j < parameterAnnotations[i].length; j++) {
//如果该参数前面的注解不为空并且是ParamCheck的实例,并且notNull()=true,并且默认值为空,则进行非空校验
if (parameterAnnotations[i][j] != null && parameterAnnotations[i][j] instanceof ParamCheck && ((ParamCheck) parameterAnnotations[i][j]).notNull() && StringUtils.isEmpty(((ParamCheck)parameterAnnotations[i][j]).defaultValue())) {
paramIsNull(paramNames[i], paranValues[i], parameterTypes[i] == null ? null : parameterTypes[i].getName());
break;
}
//如果该参数前面的注解不为空并且是ParamCheck的实例,并且默认值不为空,并且参数值为空,则进行赋默认值
if(parameterAnnotations[i][j] != null && parameterAnnotations[i][j] instanceof ParamCheck && !StringUtils.isEmpty(((ParamCheck)parameterAnnotations[i][j]).defaultValue()) && (paranValues[i] == null || StringUtils.isEmpty(paranValues[i].toString()))){
paranValues[i] = putParam(((ParamCheck)parameterAnnotations[i][j]).defaultValue(), parameterTypes[i]);
}
}
}
return pjp.proceed(paranValues);
}
/**
-
在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
-
@param joinPoint
*/
@AfterReturning(“checkParam()”)
public void doAfterReturning(JoinPoint joinPoint) {
}
/**
-
参数非空校验,如果参数为空,则抛出ParamIsNullException异常
-
@param paramName
-
@param value
-
@param parameterType
*/
private void paramIsNull(String paramName, Object value, String parameterType) {
if (value == null || “”.equals(value.toString().trim())) {
throw new ParamIsNullException(paramName, parameterType,“参数为空”);
}
}
private Object putParam(Object value, Class<?> parameterType) {
return CastValueTypeUtil.parseValue(parameterType, value.toString());
}
}
需要注意,这个路径是你准备添加校验的controller的路径,改成你自己的:
然后是校验参数里面使用到的参数转换工具类,CastValueTypeUtil.java:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*转换object类型
**/
public class CastValueTypeUtil {
public static Object parseValue(Class<?> parameterTypes, String value) {
if(value==null || value.trim().length()==0){
return null;
}
value = value.trim();
if (Byte.class.equals(parameterTypes) || Byte.TYPE.equals(parameterTypes))