I have not written an article for almost half a year, and I am finally finished with my work and can export it to the outside world. Some time ago, when submitting code review, my colleague mentioned a defect in code specification: parameter verification should be placed in the Controller layer. How should do parameter check in the end

Controller vs. Service layer

I went to the Internet to check some information. Generally, it is recommended that those not related to business should be checked in the Controller layer, while those related to business should be checked in the Service layer. So how do I make the parameter validation look nice? If it’s all if-else, I feel like I’m writing low code, but I’m glad I have wheels

Common verification tool classes

Using Hibernate Validate

Introduction of depend on

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> < version > this Final < / version > < / dependency >Copy the code

Common notes

annotations instructions
@Length(min=,max=) Check whether the length of the owning field is between min and Max
@Range(min=,max=,message=) The annotated element must be in the appropriate scope
@Max The value of this field must be less than or equal to the value
@Min The value of this field can only be greater than or equal to the value
@NotNull Cannot be null
@NotBlank The value cannot be empty. Spaces will be ignored during check
@NotEmpty It cannot be empty, where empty means an empty string
@Pattern(regex=,flag=) The annotated element must conform to the specified regular expression

Use the “@” or “Valid” annotations in Controller together. There is not much difference between the “@” and “Valid” annotations. In general, you can select one of them as follows:

annotations @Validated @Valid
Subordinate to the package Belong to the org. Springframework. Validation. The annotation package, is provided by the spring Validation is provided by the JDK and belongs to javax.validation
Whether grouping and sorting are supported is no

Although @ is more powerful than @Valid and provides grouping and verification sorting functions on top of @Valid, annotations in the hibernate-validate framework need to be added to entities in actual projects

  • Define an entity
Public class DataSetSaveVO {// The unique identifier is blank @notBlank (message = "user uuid is empty") // The user name can only be letters and numbers @pattern (regexp =) "^[a-z0-9]+$", message = "user names can only be alphabetic and numeric") @Length(max = 48, message = "user uuid length over 48 byte") private String userUuid; / / data set name can only be letters and Numbers @ the Pattern (regexp = "^ / A - Za - z0-9 + $". Message = "data set names can only be letters and Numbers") @length (Max = 48, Message = "file name too long") @notBlank (message = "file name is empty") private String name; // Data set description is at most 256 bytes @Length(Max = 256, Message = "data set description length over 256 bytes ") @notblank (message = "data set description is null") private String description; }Copy the code

Note: The message field is the exception that is thrown when the verification rule is not met

  • Methods in the Controller layer
@PostMapping
public ResponseVO createDataSet(@Valid @RequestBody DataSetSaveVO dataSetVO) {
    return ResponseUtil.success(dataSetService.saveDataSet(dataSetVO));
}
Copy the code

Note: Add the @VALID or @validated annotation next to the Validated entity DataSetSaveVO

Use the Commons – lang3

Introduction of depend on

Mons < dependency > < groupId > org.apache.com < / groupId > < artifactId > Commons - lang3 < / artifactId > < version > 3.4 < / version > </dependency>Copy the code

Common Methods

methods instructions
CollectionUtils.isEmpty Checks whether the collection is empty, null or size==0, and returns true
CollectionUtils.isNotEmpty Determines whether the set is non-empty
StringUtils.isEmpty Checks if the string is empty
StringUtils.isNotEmpty Checks if the string is not empty
StringUtils.isBlank Returns true if the string is empty, null or size==0, or if there are only whitespace characters (such as “”)
StringUtils.isNotBlank Checks whether the string is non-empty
  • The test code
//StringUtils.isEmpty
System.out.println(StringUtils.isEmpty(""));  //true
System.out.println(StringUtils.isEmpty("  "));  //false
//StringUtils.isNotEmpty
System.out.println(StringUtils.isNotEmpty(""));  //false
        
//StringUtils.isBlank
System.out.println(StringUtils.isBlank(""));  //true
System.out.println(StringUtils.isBlank(" "));  //true
//StringUtils.isNotBlank
System.out.println(StringUtils.isNotBlank(" "));  //false

List<Integer> emptyList = new ArrayList<>();
List<Integer> nullList = null;
List<Integer> notEmptyList = new ArrayList<>();
notEmptyList.add(1);

//CollectionUtils.isEmpty
System.out.println(CollectionUtils.isEmpty(emptyList));   //true
System.out.println(CollectionUtils.isEmpty(nullList));   //true
System.out.println(CollectionUtils.isEmpty(notEmptyList));   //false

//CollectionUtils.isNotEmpty
System.out.println(CollectionUtils.isNotEmpty(emptyList));   //false
System.out.println(CollectionUtils.isNotEmpty(nullList));   //false
System.out.println(CollectionUtils.isNotEmpty(notEmptyList));   //true
Copy the code
Custom annotations

When none of the above aspects meet the validation requirements, you can consider using custom annotations. How to write a custom annotation can be seen in the previous article: Spring Custom Annotations from Beginner to Master