Check field
// Check field @Valid @Validated yes@Valid One package of is Spring The provided verification mechanism is used.@Valid No grouping function is provided
Configure global exception
@Slf4j @ControllerAdvice public class GlobalExHandler { @ExceptionHandler(Exception.class) @ResponseBody public String error(Exception e) { e.printStackTrace(); return "Exception executed"; } @ExceptionHandler(BindException.class) @ResponseBody public String error(BindException e) { String msg = ""; BindingResult result = e.getBindingResult(); if (result.hasErrors()) { List<ObjectError> allErrors = result.getAllErrors(); allErrors.forEach( p -> { System.out.println(p); } ); FieldError objectError = (FieldError) allErrors.get(0); msg = objectError.getField(); msg += "-> " + objectError.getDefaultMessage(); } return msg; } @ExceptionHandler(GlobalEx.class) @ResponseBody public String error(GlobalEx e) { e.printStackTrace(); return "Custom exception executed"; } }
Custom exception
public class GlobalEx extends RuntimeException { private Integer code; private String msg; }
No grouping
After we have made the strategy of data verification, every time we request the corresponding parameters in the interface, we will check our parameters according to the verification specified by our parameters, which can avoid us writing repeated verification every time. However, for some specific scenarios, the verification rules will change. At this time, it needs to be divided into groups. For example, the id can be null when inserting, but cannot be null when updating
1. Entity class
@Data public class Teacher { @NotNull private String teacherName; @Min(4) private Integer teacherAge; }
2. Testing
@GetMapping("test") public String test(@Valid Teacher teacher) { return "Message sent.."; }
With grouping
1. Entity
@Accessors(chain = true) @Data public class Person { @NotNull(groups = PersonUpdateGroup.class) private String name; @NotBlank(groups = {PersonInsertGroup.class, PersonUpdateGroup.class}) private String address; @NotNull(groups = PersonInsertGroup.class) @Min(value = 4,groups = PersonInsertGroup.class) private Integer age; @MyValidated(message = "message") private String test; public interface PersonInsertGroup { } public interface PersonUpdateGroup { } }
2. Testing
//PersonInsertGroup is an insert group at this time, and the name can be empty. @GetMapping("send") public String send(@Validated(Person.PersonInsertGroup.class) Person person) { sender.send(); return "Message sent.."; }
Custom verification
When you write your own custom verification, you can directly imitate what has been written. In fact, it is a custom annotation. Just pay attention to the left and right range of the annotation and the required fields
1. Write custom annotations
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint( validatedBy = {MyValidatedImpl.class} ) public @interface MyValidated { String message() default "{javax.validation.constraints.NotNull.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
2. Verification rules for writing annotations
The verification rule only needs to implement one interface. Pay attention to its generic requirements
- One requirement is annotation
- Annotation generic, which can be called in the initialization method
- One is random type
- Can be called in the verified method
public interface ConstraintValidator<A extends Annotation, T> { default void initialize(A constraintAnnotation) { } boolean isValid(T var1, ConstraintValidatorContext var2); }
public class MyValidatedImpl implements ConstraintValidator<MyValidated, String> { @Override public void initialize(MyValidated myValidated) { // The message is printed System.out.println("MyValidated - >" + myValidated.message()); } @Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { /** * Get the fields to be checked entered by the user */ String ans = "test"; System.out.println("isValid - > " + value); if (ans.equals(value)) { ConstraintValidatorContext.ConstraintViolationBuilder test = constraintValidatorContext.buildConstraintViolationWithTemplate("Cannot contain test"); return false; } else { return true; } } }
3. Testing
@MyValidated(message = "message") private String test;
Common verification rules
annotation | explain |
---|---|
@Null | Restriction can only be Null |
@NotNull | Restriction must not be null |
@AssertFalse | Restriction must be false |
@AssertTrue | Restriction must be true |
@DecimalMax(value) | The limit must be a number no greater than the specified value |
@DecimalMin(value) | The limit must be a number not less than the specified value |
@Digits(integer,fraction) | The limit must be one decimal, and the number of digits in the integer part cannot exceed integer, and the number of digits in the decimal part cannot exceed fraction |
@Future | Limit must be a future date |
@Max(value) | The limit must be a number no greater than the specified value |
@Min(value) | The limit must be a number not less than the specified value |
@Past | Limit must be a past date |
@Pattern(value) | The restriction must conform to the specified regular expression |
@Size(max,min) | The limit character length must be between min and max |
@NotEmpty | The element value of the validation annotation is not null and empty (string length is not 0, collection size is not 0) |
@NotBlank | The element value of the verification annotation is not null (it is not null, and the length is 0 after removing the first space). Unlike @ NotEmpty, @ NotBlank is only applied to strings, and the spaces of strings will be removed during comparison |
Verify that the element value of the annotation is email. You can also specify a custom email format through regular expression and flag |