Hibernate validator usage and custom validator annotation

Time:2020-5-14

Jsr-303 is a sub specification in Java EE 6, called bean validation, which is used to validate the values of fields in java bean. Hibernate validator is an implementation of this specification provided by hibernate.

——Hibernate validator is used for parameter verification.

Use the annotation provided by hibernate validator for parameter verification

annotation interpretation
@Null Must be null
@NotNull Cannot be null
@AssertTrue Must be true
@AssertFalse Must be false
@Min Must be a number with a value greater than or equal to the specified minimum
@Max Must be a number with a value less than or equal to the specified maximum
@DecimalMin Must be a number with a value greater than or equal to the specified minimum
@DecimalMax Must be a number with a value less than or equal to the specified maximum
@Size Length of set
@Digits Must be a number whose value must be within the acceptable range
@Past Must be a date in the past
@Future Must be a future date
@Pattern Must conform to regular expression
@Email Must be in mailbox format
@Length Length range
@NotEmpty Cannot be null, length greater than 0
@Range Size range of elements
@NotBlank Cannot be null, string length is greater than 0 (string limit)

Introduce dependency


<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>6.0.15.Final</version>
</dependency>

Hibernate validator common annotations

Create test class

Note that null judgment must be performed first, otherwise some other annotations will not take effect.
For example, @ length is added to username without @ notnull annotation. If username is not entered, @ length judgment will not take effect, and @ notnull, @ notempty and @ notblank are null
It is recommended to remove @ notnull and test again

package com.dfyang.validator.entity;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;

public class User {
 @Notblank (message = "name cannot be empty")
 private String name;

 @Range (min = 1, max = 120, message = "age must be 1-120")
 private Integer age;

 @Notblank (message = "description cannot be empty")
 private String description;

 @NotNull
 @Length (min = 6, max = 18, message = "user name length must be 6-18 digits")
 private String username;

 @NotNull
 @Length (min = 6, max = 18, message = "password length must be 6-18 bits")
 private String password;

 /**Get, set method*/
}

Create test controller

@Valid is used on the parameter to verify the parameter.

If an error is found in the parameter verification, the error will be injected into the bindingresult

We can print the error here or throw an exception directly


package com.dfyang.validator.controller;

import com.dfyang.validator.entity.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class UserController {

 @GetMapping("/insert")
 @ResponseBody
 public User insertUser(@Valid User user, BindingResult result) {
  if (result.hasErrors()) {
   for (ObjectError error : result.getAllErrors()) {
    System.err.println(error.getDefaultMessage());
   }
  }
  return user;
 }
}

Enter http: / / localhost: 8080 / insert? Name = Zhang San & Description = & age = 0 & username = 123123

Parameter verification with custom verifier

Create a custom annotation to determine whether the age meets the constraint

package com.dfyang.validator.constraint;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *Gender constraints
 */
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SexConstraintValidator.class)
public @interface Sex {

 String message() default "wrong gender";

 Class<?>[] groups() default { };

 Class<? extends Payload>[] payload() default { };
}

Judge whether the value of the annotation conforms to the constraint. Here we make a null judgment, or we can not add another @ nutnull

package com.dfyang.validator.constraint;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 *Logical judgment of gender restriction
 */
public class SexConstraintValidator implements ConstraintValidator<Sex, String> {
 @Override
 public boolean isValid(String value, ConstraintValidatorContext context) {
  Return value! = null & & (value.equals ("male") | value.equals ("female"));
 }
}

@Target is used to specify the scope of use, which can only be used on the field
@Retention( RetentionPolicy.RUNTIME )Indicates that annotations can be obtained by reflection at runtime
@Constraint (validatedby = XXX. Class) specifies the annotation verification logic

2. Create a verification entity, and use hibernate validator’s own annotations and customized annotations

package com.dfyang.validator.entity;

import com.dfyang.validator.constraint.Sex;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

public class User {
 @Notblank (message = "name cannot be empty")
 private String name;

 @Range (min = 1, max = 120, message = "age must be 1-120")
 private Integer age;

 @Sex
 private String sex;

 @Notblank (message = "description cannot be empty")
 private String description;

 @Notnull (message = "user name cannot be empty")
 @Length (min = 6, max = 18, message = "user name length must be 6-18 digits")
 private String username;

 @Notnull (message = "password cannot be empty")
 @Length (min = 6, max = 18, message = "password length must be 6-18 bits")
 private String password;
 
 /**Omit get, set*/
}

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.