美文网首页
JSR-303 非Controller验证

JSR-303 非Controller验证

作者: rarexixi | 来源:发表于2018-08-01 16:11 被阅读0次

    自定义切面

    ResultVo 自行定义

    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.validation.annotation.Validated;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Validator;
    import java.lang.reflect.Method;
    import java.lang.reflect.Parameter;
    import java.util.*;
    
    @Component
    @Aspect
    public class ValidateAspect {
    
        @Autowired
        Validator validator;
    
        /**
         * 设置标识
         */
        @Pointcut("execution(public * xxx.*.*(..))")
        public void invoke() {
        }
    
    
        /**
         * 环绕方法执行,proceedingJoinPoint.proceed()是执行环绕的方法
         *
         * @param proceedingJoinPoint
         * @return
         * @throws Throwable
         */
        @Around("invoke()")
        public Object Test(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    
            String methodName = "";
            try {
                MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
                Method method = methodSignature.getMethod();
                Parameter[] parameters = method.getParameters();
                Object[] args = proceedingJoinPoint.getArgs();
    
                List<String> messages = new LinkedList<>();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    Validated validated = parameter.getAnnotation(Validated.class);
                    if (validated == null) continue;
                    Set<ConstraintViolation<Object>> validateResults = validator.validate(args[i], validated.value());
                    for(ConstraintViolation<Object> constraintViolation : validateResults) {
                        String message = constraintViolation.getMessage();
                        messages.add(message);
                    }
                }
                if (!messages.isEmpty()) {
                    return new ResultVo<>(messages);
                }
    
                return proceedingJoinPoint.proceed();
            } catch (Exception e) {
                // log
            }
    
            return new ResultVo<>("系统错误");
        }
    }
    

    相关文章

      网友评论

          本文标题:JSR-303 非Controller验证

          本文链接:https://www.haomeiwen.com/subject/kfjrvftx.html