You're still using if else... Check the parameters from the front end? Are you still checking parameters with code? If so, your project verification is not perfect.
Xiaobian here shares the parameter verification through annotation, farewell to if else... The era of!!!
This article mainly introduces Javax ValidationI annotation verification architecture, which is simple, convenient, quick to start, convenient to expand and simple to expand. It is suitable for small partners who use annotation verification for the first time.
If it is a Spring project, the schema dependency will be automatically referenced. If it is a non Spring project, you need to manually reference the dependency. This article focuses on Spring project:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1</version> </dependency>
This is the element in the annotation package:
- @AssertFalse the annotated element must be false
- @AssertTrue the annotated element must be true
- @DecimalMax(value) the annotated element must be a number whose value must be less than or equal to the specified maximum value
- @DecimalMin(value) the annotated element must be a number whose value must be greater than or equal to the specified minimum value
- @The annotated element of Digits (integer, fraction) must be a number, and its value must be within the acceptable range
- @The annotated element of Email must be Email address
- @Future annotated element must be a future date
- @Max(value) the annotated element must be a number whose value must be less than or equal to the specified maximum value
- @Min(value) the annotated element must be a number whose value must be greater than or equal to the specified minimum value
- @NotBlank verify that the element value of the annotation is not empty (not null and remove the leading and trailing spaces)
- @NotEmpty verify that the element value of the annotation is not null and empty (string length is not 0, collection size is not 0)
- @NotNull is not null
- @Null is null
- @The Past limit must be a date in the Past
- @Pattern(value) restriction must conform to the specified regular expression
- @Size(max,min) `B limit character length must be between min and Max
Validation rule
- In the Spring project, define a model to verify as follows:
@Data public class ValidatorModel { @NotBlank(message = "Name cannot be empty") private String name; @Size(min = 3, max = 6) private List<String> friendNames; @Min(value = 18, message = "Under 18") @Max(value = 60, message = "Age must be under 60") private Integer age; private String tel; @DecimalMin(value = "30", message = "Money cannot be less than 30") private BigDecimal money; }
- The contents of the service interface are as follows:
Because it's the verification framework of javax, it can also be verified without Spring. The annotation must be written on the interface. If it is written on the implementation class, it will be invalid!!!
//Open validation comment @Validated public interface ValidatorService { void validator(@Valid ValidatorModel model, @NotNull String param); }
The service implementation class is normal logic processing, which is not shown here.
- The content of controller is as follows:
The controller receives the parameter and passes it to the service. It verifies the parameter in the service interface. If it fails, an exception will be thrown.
@RestController public class ValidatorController { @Autowired private ValidatorService validatorService; @GetMapping public void validator() { ValidatorModel model = new ValidatorModel(); model.setName("Zhang San"); model.setFriendNames(Arrays.asList("Li Si", "Wang Wu")); model.setAge(20); model.setTel("188888888881"); model.setMoney(new BigDecimal(100)); validatorService.validator(model,"You can also verify the parameters"); } }
Abnormal screenshot:
The above is a common method for Javax Validation verification, which can meet most of the situations
-
All parameters need to be verified when adding, and only a few parameters or parameters with values need to be verified (Group verification) when updating.
-
Can I customize the validation rules? I want to verify the gender. It can only be male or female (customize the validation rules).
Group verification
When adding, the friendNames field needs to be verified, and when updating, the name field needs to be verified. At this time, group verification needs to be referenced. Modify the validator model as follows:
@Data public class ValidatorModel { /** * Add grouping */ public interface Create { } /** * Update packet */ public interface Update { } /** * Multiple groups can be specified, represented by {} * Group as: default group, update group */ @NotBlank(message = "Name cannot be empty", groups = {Default.class, Update.class}) private String name; /** * Group as add group */ @Size(min = 3, max = 6, groups = {Create.class}) private List<String> friendNames; @Min(value = 18, message = "Under 18") @Max(value = 60, message = "Age must be under 60") private Integer age; private String tel; @DecimalMin(value = "30", message = "Money cannot be less than 30") private Integer money; }
Do not change the ValidatorService interface. Add grouping parameters to the ValidatorService implementation class, as follows:
@Validated @Service public class ValidatorServiceImpl implements ValidatorService { @Override public void validator(@Validated(ValidatorModel.Create.class) ValidatorModel model, String param) { } }
This enables group verification.
Note: there is a default group in the model. If you specify a group, the parameters will be verified by group. If you do not specify a group, it belongs to the default group. The ValidatorServiceImpl above will not verify the default group. Write @ Validated({ValidatorModel.Create.class, Default.class}) to add the default group to the validation. As follows:
@Validated @Service public class ValidatorServiceImpl implements ValidatorService { @Override public void validator(@Validated({ValidatorModel.Create.class, Default.class}) ValidatorModel model, String param) { } }
Custom validation rules
What if I want to verify my cell phone? It's not provided in it. Don't panic the children. It's OK to use custom annotation verification. It provides an interface that we just need to implement.
First of all, we need to define a MonkeyTel to verify the phone number, and specify its implementation class. It is OK to write the verification logic. The notes are as follows:
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.FIELD}) // Specify classes that actually implement validation rules @Constraint(validatedBy = MonkeyTelImpl.class) public @interface MonkeyTel { String message() default "Mobile number must be 11 digits"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
The implementation classes are as follows:
/** * @Author: LailaiMonkey * @Description: * String: Parameter type * @Date: Created in 2020-04-17 15:19 * @Modified By: */ public class MonkeyTelImpl implements ConstraintValidator<MonkeyTel, String> { /** * The cell phone number is "ture" * @param value value * @param context * @return */ @Override public boolean isValid(String value, ConstraintValidatorContext context) { return value.length() == 11; } }
- The project structure is as follows:
Custom validation rules
- Disadvantages:
This annotation can only be used if there is an interface or Controller. It is invalid if it is written on an implementation class. Moreover, the logic is written on the implementation class. You don't know which parameters to verify. You have to return to the interface or Controller to query.
It does not support List collection verification, which is difficult to implement. It only supports simple model verification.
Advantages: user defined annotations are easy to implement and fast to use.
To sum up, the editor has developed a set of user-defined annotations by using Spring AOP. It has good extensibility and the bottom layer has been written. We just need to define and implement the annotations as above, and then specify the three steps to inject annotations into the specified class.