This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package jnpf.util;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 验证类
|
||||
*
|
||||
* @author lx
|
||||
* @version 1.0
|
||||
* @since 2021-10-26
|
||||
*/
|
||||
public class ValidatorUtils {
|
||||
private static Validator validator;
|
||||
|
||||
static {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验对象
|
||||
*
|
||||
* @param object 待校验对象
|
||||
* @param groups 待校验的组
|
||||
* @throws ServiceException 校验不通过,则报自定义异常
|
||||
*/
|
||||
public static void validateEntity(Object object, Class<?>... groups)
|
||||
throws ServiceException {
|
||||
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
|
||||
if (!constraintViolations.isEmpty()) {
|
||||
ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
|
||||
throw new ServiceException(constraint.getMessage(), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user