spring boot 使用Validated

pom依赖

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

aop切面


import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.Set;

/**
 * @author chunyang.leng
 * @date 2021/1/26 9:09 上午
 */
@Aspect
@Component
public class ParamCheckAOP {

    @Pointcut("execution(public * com.xxx.xxx.controller.*.*(..))")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object validation(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();

        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        Method declaredMethod = joinPoint.getTarget().getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
        Annotation[][] parameterAnnotations = declaredMethod.getParameterAnnotations();
        for (int i = 0; i < parameterAnnotations.length; i++) {
            Object param = args[i];
            int length = parameterAnnotations[i].length;
            for (int j = 0; j < length; j++) {
                Annotation annotation = parameterAnnotations[i][j];
                if (annotation instanceof Validated) {
                    if (Objects.isNull(param)) {
                        // todo 自定义异常
                        throw new ParamCheckException("必填项不能为空");
                    }
                    Validated validated = (Validated) annotation;
                    Class<?>[] classList = validated.value();
                    String validResult = valid(param, classList);
                    if (StringUtils.isNotEmpty(validResult)) {
                        // todo 自定义异常
                        throw new ParamCheckException(validResult);
                    }
                }
            }
        }
        return joinPoint.proceed();
    }

    private String valid(Object obj, Class[] clazz) {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<Object>> validate = validator.validate(obj, clazz);
        StringBuffer stringBuffer = new StringBuffer();
        validate.forEach(o -> {
            String message = o.getMessage();
            if (StringUtils.isNotBlank(message)) {
                stringBuffer.append(message).append("\n");
            }
        });
        return stringBuffer.toString();
    }
}

自定义异常

/**
 * @author chunyang.leng
 * @date 2021/1/26 9:47 上午
 */
public class ParamCheckException extends RuntimeException{
    private String message;
    /**
     * Constructs a new runtime exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public ParamCheckException(String message) {
        super(message);
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

统一异常处理


import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author chunyang.leng
 * @date 2021/1/26 9:48 上午
 */
@RestControllerAdvice
public class ParamCheckControllerAdvice {

    @ExceptionHandler(value = ParamCheckException.class)
    public JSONObject check(ParamCheckException e){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","error");
        jsonObject.put("message",e.getMessage());
        return jsonObject;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北漂的菜小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值