一、参数校验工具类
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Path;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
public final class ValidatorUtils {
private static Validator validator;
static {
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
.configure()
.addProperty( "hibernate.validator.fail_fast", "true" )
.buildValidatorFactory();
validator = validatorFactory.getValidator();
}
public static String validate(Object param) {
Set<ConstraintViolation<Object>> violationSet = validator.validate(param);
for (ConstraintViolation<Object> model : violationSet) {
for (Path.Node node : model.getPropertyPath()) {
if (!StringUtils.isEmpty(node.getName())) {
return model.getMessage() + "(" + node.getName() + ")";
}
}
}
return null;
}
}
二、参数校验接口,所有入参类都要继承IParam
public interface IParam {
default void validate(){
String msg = ValidatorUtils.validate(this);
if (!StringUtils.isEmpty(msg)){
throw new WebException(ErrorCodeEnum.PARAM_ERROR, msg);
}
}
default void validate(String errorMsgPrefix){
String msg = ValidatorUtils.validate(this);
if (!StringUtils.isEmpty(msg)){
throw new WebException(ErrorCodeEnum.PARAM_ERROR, errorMsgPrefix + msg);
}
}
}