preface
Those of you who are doing SpringMVC development will certainly use validation to ensure that the input parameters are valid, and this is the back-end validation. As shown below, Hibernate can mostly meet our needs for normal validation, but if we encounter one that doesn’t, we can customize it, such as: phone number validation.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1. The Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16. The Final</version>
</dependency>
Copy the code
After introducing the validation framework, take a look at the following example to see if you recall writing similar code.
@Data
public class Teacher {
@NotBlack // Normal annotations can be divided into groups
private String name;
@Valid // This annotation validates the attributes annotated in the Student object
private List<Student> students;
}
public class TeacherController {
// The @validated parameter can be used to verify the current handleMethod parameter. Here, the packet verification can be used
public Teacher getInfo(@Validated Teacher teacher) {}}Copy the code
So, for a special field, need to carry out a special check, we need to customize the check, the following details how to customize the check.
Step 1: Customize validation annotations
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
// Specify a validation annotator
@Constraint(validatedBy = NameValidatorClass.class)
public @interface Name {
// The value of the annotation can be received
String value(a) default "";
// Check failed, and a message is displayed
String message(a) default "username is not null"; Class<? >[] groups()default {};
Class<? extends Payload>[] payload() default {};
}
Copy the code
If a property field in an annotation does not have a default value, it is a required field in the annotation. Custom validation annotations require binding validation annotations.
Step 2: Customize the validation annotator
public class NameValidatorClass implements ConstraintValidator<Name.String> {
private String value;
/** * Initialize the value in the annotation *@paramName Custom annotation *@return void
**/
@Override
public void initialize(Name name) {
// Get the attribute value in the custom annotation
this.value = name.value();
}
/** * check the value *@paramValue Specifies the value to be checked for submission *@paramContext Context *@returnTrue indicates that the verification succeeds. False indicates that the verification fails. Message **/ is thrown
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return !"".equals(value); }}Copy the code
Step 3: Use custom annotations
@Data
public class User {
@Name(groups = {Add.class})
private String name;
}
@PostMapping("/hello")
public R addUser(@Validated({Add.class}) User user) {
return R.ok();
}
Copy the code
conclusion
Since the validation failure will throw an exception, and since SpringMVC recommends universal exception handling, we only need the global exception handler to catch the validation failure exception and return the exception result to the front end in JSON format.