javax.validation校验工具类

javax.validation校验工具类,第1张

package com.zy.platform.common.core.utils;

import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.StringJoiner;

public class ValidatorUtil {
    public static void doValidate(Object o) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set> constraintViolations = validator.validate(o, Default.class);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append(".");
            }
            throw new RuntimeException(msg.toString());
        }
    }

    public static void doValidate(Object o, String[] validateAttr) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        StringJoiner sj = new StringJoiner(";");
        for (String s : validateAttr) {
            Set> constraintViolations = validator.validateProperty(o, s, Default.class);
            if (!constraintViolations.isEmpty()) {
                StringBuilder msg = new StringBuilder();
                for (ConstraintViolation constraint : constraintViolations) {
                    msg.append(constraint.getMessage()).append(".");
                }
                sj.add(msg.toString());
            }
        }
        if(StringUtils.isNotBlank(sj.toString())){
            throw new RuntimeException(sj.toString());
        }
    }

    public static void doValidate(Object o,Class cla) {

        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set> constraintViolations = validator.validate(o, cla);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append(".");
            }
            throw new RuntimeException(msg.toString());
        }

    }
}
 
GlobalExceptionHandler:
package com.zy.platform.common.core.exception;

import com.zy.platform.common.core.web.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author javachen
 * @description 全局异常处理类
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler{

    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public ServerResponse customException(CustomException e){
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        if(null!=e.getCode()){
            return ServerResponse.createByErrorCodeMessage(e.getCode(),e.getMessage());
        }else{
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)//指定出现什么异常执行这个方法
    public ServerResponse error(Exception e){
        log.error("自定义异常信息 ex={}", e.getMessage(), e);
        return ServerResponse.createByErrorMessage(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ServerResponse MyExceptionHandle(MethodArgumentNotValidException exception){
        exception.printStackTrace();
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder() ;

        if (result.hasErrors()) {
            List fieldErrors = result.getFieldErrors();
            exception.printStackTrace();
            return ServerResponse.createByErrorMessage(fieldErrors.get(0).getDefaultMessage().toString());
        }
        return ServerResponse.createBySuccess();
    }

}

test:

   //进行参数校验
   ValidatorUtil.doValidate(sysUserAddBO,Insert.class);

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/917246.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)