1、Hibernate Validator介绍
Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。Bean Validation 为 JavaBean 验证定义了相应的元数据模型和API。缺省的元数据是 Java Annotations,通过使用 XML 可以对原有的元数据信息进行覆盖和扩展。Bean Validation 是一个运行时的数据验证框架,在验证之后验证的错误信息会被马上返回。
2、maven 的pom.xml引用
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
3、自定义注解示例
校验字符串类型的时间格式是否符合指定格式。
import org.apache.commons.lang3.StringUtils;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.text.SimpleDateFormat;
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateString.Validator.class)
@Documented
public @interface DateString {
String message() default "时间格式有误,要求时间格式:yyyy-MM-dd HH:mm:ss";
String format() default "yyyy-MM-dd HH:mm:ss";
boolean allowBlank() default false;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default{};
class Validator implements ConstraintValidator<DateString, String> {
boolean allowBlank;
String dataFormat = "yyyy-MM-dd HH:mm:ss";
String message;
@Override
public void initialize(DateString constraintAnnotation) {
allowBlank = constraintAnnotation.allowBlank();
dataFormat = constraintAnnotation.format();
message = constraintAnnotation.message();
}
@Override
public boolean isValid(String arg0, ConstraintValidatorContext arg1) {
if(!allowBlank && StringUtils.isNotBlank(arg0) && arg0.trim().length() == dataFormat.length()){
try {
// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
SimpleDateFormat format = new SimpleDateFormat(dataFormat);
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(arg0);
return true;
} catch (Exception e) {
//重定义错误模板
arg1.disableDefaultConstraintViolation();
arg1.buildConstraintViolationWithTemplate(message).addConstraintViolation();
return false;
}
}
return true;
}
}
}
4、注解使用:
@DateString(message = "issuTime时间格式有误,要求时间格式:yyyy-MM-dd HH:mm:ss")
String issuTime;
5、重新定义默认的错误信息模板
两种方式:
第一种:
//禁用默认的message的值
arg1.disableDefaultConstraintViolation();
//重定义新的错误
arg1.buildConstraintViolationWithTemplate(message).addConstraintViolation();
第二种:
在resource 目录下新建提示信息配置文件“ValidationMessages.properties“。名字必须为“ValidationMessages.properties“ 因为SpringBoot自动读取classpath中的ValidationMessages.properties里的错误信息。
ValidationMessages.properties 文件的编码为ASCII。
date.str=issuTime\u65f6\u95f4\u683c\u5f0f\u6709\u8bef\uff0c\u8981\u6c42\u65f6\u95f4\u683c\u5f0f\uff1ayyyy-MM-dd HH:mm:ss
内容:date.str=issuTime时间格式有误,要求时间格式:yyyy-MM-dd HH:mm:ss
6、自定义注解中 @Target、@Retention、@Documented简单说明
@Target
rget批注标记另一个批注,以限制批注可以应用于何种Java元素。
package java.lang.annotation;
/**
* The constants of this enumerated type provide a simple classification of the
* syntactic locations where annotations may appear in a Java program. These
* constants are used in {@link Target java.lang.annotation.Target}
* meta-annotations to specify where it is legal to write annotations of a
* given type.
* @author Joshua Bloch
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 4.1 The Kinds of Types and Values
*/
public enum ElementType {
/** 类, 接口 (包括注释类型), 或 枚举 声明 */
TYPE,
/** 字段声明(包括枚举常量) */
FIELD,
/** 方法声明(Method declaration) */
METHOD,
/** 正式的参数声明 */
PARAMETER,
/** 构造函数声明 */
CONSTRUCTOR,
/** 局部变量声明 */
LOCAL_VARIABLE,
/** 注释类型声明 */
ANNOTATION_TYPE,
/** 包声明 */
PACKAGE,
/**
* 类型参数声明
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* 使用的类型
*
* @since 1.8
*/
TYPE_USE
}
@Retention
这个枚举类型的常量描述保留注释的各种策略。
package java.lang.annotation;
/**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
public enum RetentionPolicy {
/**
* 注释只在源代码级别保留,编译时被忽略
*/
SOURCE,
/**
* 注释将被编译器在类文件中记录
* 但在运行时不需要JVM保留。这是默认的
* 行为.
*/
CLASS,
/**
*注释将被编译器记录在类文件中
*在运行时保留VM,因此可以反读。
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Documented
注解表明这个注释是由 javadoc记录的,在默认情况下也有类似的记录工具。 如果一个类型声明被注释了文档化,它的注释成为公共API的一部分。
@Inherited
表明注解类型可以从超类继承。当用户查询注释类型而该类没有对此类型的注释时,将查询类的超类以获取注释类型。此注释仅应用于类声明。
当一个类继承了拥有此注解的类时,即使当前类没有任何注解。 只要父类的注解拥有(@Inherited)属性,则在子类中可以获取到此注解。
@Repeatable
注解表明标记的注解可以多次应用于相同的声明或类型使用。
本文详细介绍HibernateValidator的功能,包括JSR303规范的所有内置约束实现,以及如何在Maven项目中引入依赖。此外,还提供了自定义注解的示例,用于校验字符串类型的时间格式,并展示了如何重新定义错误信息模板。
955

被折叠的 条评论
为什么被折叠?



