Parameter verification in JAVA by Hibernate Validation
- 2021-07-18 07:58:38
- OfStack
When developing JAVA server-side code, we will encounter verifying the validity of externally transmitted parameters, while hibernate-validator provides some common parameter verification comments, which we can use.
1. Introduce jar corresponding to hibernate-validator into maven:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
2. Define the fields to validate in Model:
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class PayRequestDto {
/**
* Payment completion time
**/
@NotEmpty(message=" Payment Completion Time cannot be empty ")
@Size(max=14,message=" Payment completion time cannot exceed {max} Bit ")
private String payTime;
/**
* Status
**/
@Pattern(regexp = "0[0123]", message = " Status can only be 00 Or 01 Or 02 Or 03")
private String status;
public String getPayTime() {
return payTime;
}
public void setPayTime(String payTime) {
this.payTime = payTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
3. Define the Validation tool class:
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.HibernateValidator;
import com.atai.framework.lang.AppException;
public class ValidationUtils {
/**
* Use hibernate To validate the annotations of
*
*/
private static Validator validator = Validation
.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
/**
* Functional description : <br>
* Annotation Validation Parameters
*
* @param obj
* @see [ Correlation class / Method ]( Optional )
* @since [ Products / Module version ]( Optional )
*/
public static <T> void validate(T obj) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
// Throw a check exception
if (constraintViolations.size() > 0) {
throw new AppException("0001", String.format(" Parameter verification failed :%s", constraintViolations.iterator().next().getMessage()));
}
}
}
4. Call the tool class in the code for parameter validation:
ValidationUtils.validate(requestDto);
The following is a description of some annotations in hibernate-validator:
@AssertTrue | 用于boolean字段,该字段只能为true |
@AssertFalse | 该字段的值只能为false |
@CreditCardNumber | 对信用卡号进行1个大致的验证 |
@DecimalMax | 只能小于或等于该值 |
@DecimalMin | 只能大于或等于该值 |
@Digits(integer=,fraction=) | 检查是否是1种数字的整数、分数,小数位数的数字 |
检查是否是1个有效的email地址 | |
@Future | 检查该字段的日期是否是属于将来的日期 |
@Length(min=,max=) | 检查所属的字段的长度是否在min和max之间,只能用于字符串 |
@Max | 该字段的值只能小于或等于该值 |
@Min | 该字段的值只能大于或等于该值 |
@NotNull | 不能为null |
@NotBlank | 不能为空,检查时会将空格忽略 |
@NotEmpty | 不能为空,这里的空是指空字符串 |
@Null | 检查该字段为空 |
@Past | 检查该字段的日期是在过去 |
@Pattern(regex=,flag=) | 被注释的元素必须符合指定的正则表达式 |
@Range(min=,max=,message=) | 被注释的元素必须在合适的范围内 |
@Size(min=, max=) | 检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等 |
@URL(protocol=,host,port) | 检查是否是1个有效的URL,如果提供了protocol,host等,则该URL还需满足提供的条件 |
@Valid | 该注解主要用于字段为1个包含其他对象的集合或map或数组的字段,或该字段直接为1个其他对象的引用,这样在检查当前对象的同时也会检查该字段所引用的对象 |