7.13 Correctly use Validation to implement parameter validation in SpringBoot

CSDN achieves 100 million technical people


Preface

Let’s talk about Spring Validation parameter verification first. It is one of the tasks that must be done by the SpringBoot backend Controller layer of the front-end and back-end separation project. The purpose is to prevent illegal calls. The Java JSR303verification standard is defined validation-apibut not implemented. Hibernate validation is a standardized implementation. In addition, some annotations were added constraints, and finally a secondary encapsulation was Spring Validationperformed Hibernate validationto support automatic verification in SpringMvc!

So, now that the Restful style is popular, in SpringBoot, the mainstream parameter verification scenarios include:

  1. For POSTrequests PUT, use the parameters passed by @RequestBody to verifyVO对象
  2. For GET、DELETErequests, use the parameters passed by @RequestParamurl拼接 to verify
  3. Unannotated parameter verification for GET requests

Next, I will show you the correct use of @Valid , @Validated and constraints with a combination of pictures and texts. They must be used in work and practiced in practice. Finally, there is a summary , Let's Go!

The constraints annotation defined by Java's standard is located at: javax.validation.constraints

The constraints annotations added to Hibernate validation are located at: org.hibernate.validator.constraints

The perfect partner for parameter verification: 7.11 SpringBoot practical global exception handling - in-depth explanation


Introduce Maven dependencies

Before springboot2.3 , dependencies spring-boot-starter-webwere automatically introduced when introduced.validation

But after springboot2.3 , dependencies need to be introduced separatelyspring-boot-starter-validation

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

1. POST/PUT @RequestBody parameter verification

For POSTrequests PUT, it is preferred to use @RequestBodypass VO对象parameters.

1.1 Valid or Validated annotation combined with constraints annotation

Take BookAdminController's saveBook as an example:

  • Add annotations before method parameters @Valid( @Validatedyou can also replace them with annotations):

Insert image description here

  • Add annotations BookVOto the fields of the object , for example, add an annotation toconstraintsbookName@NotNull

Insert image description here

1.2 Test run

Insert image description here

If the input parameters are not filled in bookName, they will be caught by the exception of parameter verification exceptionMethodArgumentNotValidException , and finally the result shown in the figure above will be returned~

Insert image description here


2. GET/DELETE @RequestParam parameter verification

For GET、DELETErequests, it is preferred to use @RequestParampassed url拼接parameters.

2.1 Validated annotation and constraints annotation

Take BookAdminController's getBook as an example:

At this time, you need to add annotations to the Controller and add annotations @Validatedbefore the method parameters . Take annotations as an example:constraints@Min

Insert image description here

2.2 Test run

Insert image description here

Because @Minthe minimum value is limited to 1, when calling with input id=0parameters, it will be caught by the parameter verification exception exception ConstraintViolationException:

Insert image description here


3. GET unannotated parameter verification

constraintsAdd annotation before @RequestParam . It can be used if there are few parameters. When there are many parameters, it is recommended to encapsulate it into a VO object. The calling method remains the same~

3.1 Valid or Validated annotation combined with constraints annotation

Taking the getBookCommentList of BookAdminController as an example, it was originally written like this:

Insert image description here

Now the parameters are encapsulated into an PageVOobject, and annotations are added to the fields constraints: @Min, @Max,@NotNull

@Data
public class PageVO implements Serializable {
    
    
    @Min(value = 1, message = "pageNum必须大于1")
    private Integer pageNum = 1;

    @Max(value = 100, message = "pageSize不能超过100")
    private Integer pageSize = 100;

    @Min(value = 1, message = "id必须大于1")
    @NotNull
    private Integer id;
}

At this time, in the same way as @RequestBody parameter verification and annotation, add @Validannotations to the method parameters ( @Validatedyou can also change to annotations):

Insert image description here

3.2 Test run

Insert image description here

Because @Maxthe maximum value of pageSize is limited to 100, when calling with input pageSize=1000parameters, it will be caught by the exception of parameter verificationBindException exception:

Insert image description here


Summarize

  • @ValidPOST/PUT @RequestBody parameter verification, add or before the method parameter VO , and add relevant comments @Validatedto the VO fieldconstraints
  • GET/DELETE @RequestParam parameter verification, add it on the Controller , and add relevant comments @Validatedbefore the method parameters.constraints
  • @ValidGET has no annotation parameter verification, add or before the method parameter VO , and add relevant annotations @Validatedto the VO field.constraints

For constraintsrelevant details, I have found two articles for your reference:

Powerful Spring's spring validation

Detailed explanation of Hibernate Validator


at last

If you see this and find it helpful, please brush 666. Thank you for your support~

If you want to read more good practical articles, I would like to recommend my practical column –> "Practical Combination of Front-End and Front-End Separation Projects Based on SpringBoot+SpringCloud+Vue", a column jointly created by me and the front-end dog brother, which allows you to start from Quickly acquire enterprise-level standardized project practical experience from 0 to 1!

The specific advantages, planning, and technology selection can be read in the " Opening Chapter "!

After subscribing to the column, you can add my WeChat account and I will provide targeted guidance for each user!

In addition, don’t forget to follow me: Tiangang gg , in case you can’t find me, it’s not easy to miss new articles: https://blog.csdn.net/scm_2008

Guess you like

Origin blog.csdn.net/scm_2008/article/details/132790737