当前位置:网站首页>@The solution of data validation with validate or @ valid annotation

@The solution of data validation with validate or @ valid annotation

2020-12-07 21:04:58 Irving the procedural ape

@validate or @valid Annotation solution for data validation

Catalog
  • @validate or @valid Annotation solution for data validation
    • JSR Specification proposal
    • Depend on the introduction of
    • JSR303 The type of validation defined
    • @Valid and @Validated The difference between
      • Annotation position
      • grouping
      • Nested validation
    • Use BindingResult Receive the verification result information
    • Unified exception handling

When we provide external interfaces , To improve safety , We need to do data verification in the back end . actually ,Java As early as 2009 It was proposed in Bean Validation standard , The specification defines a runtime data validation framework , After verification, the error information verified will be returned immediately . And have experienced JSR303、JSR349、JSR380 The top of three standards , It's here 2.0 . The following is the specification of the data validation , And the corresponding technical framework for daily use .

JSR Specification proposal

JSR:Java Specification Requests Abbreviation , intend Java Specification proposal . It's pointing JCP(Java Community Process) A formal request to add a standardized technical specification . Anyone can submit JSR, In order to Java The platform adds new API And the service ,JSR Has become Java An important standard in the world .
This paper introduces Bean Validation It comes from JSR303,JSR349, as well as JSR380 Specification proposal . The specification is based on JSR 303 Develop to JSR 380, At present, the latest specification is Bean Validation 2.0.
I believe there are friends who want to see what it is . Address of normative proposal :https://jcp.org/en/jsr/summary?id=bean+validation

It should be noted that , The specification proposal only provides the specification , No specific implementation is provided . Specific implementation framework has default javax.validation.api, as well as hibernate-validator. At present, most of them use hibernate-validator.

Depend on the introduction of

To verify with annotations , The following two dependencies need to be introduced :

<dependency>	<groupId>javax.validation</groupId>	<artifactId>validation-api</artifactId>	<version>2.0.1.Final</version></dependency><dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.20.Final</version></dependency>

As far as I find out : 2.2.9.RELEASE Version of spring-boot-starter-web Introduced in spring-boot-starter-validation , and spring-boot-starter-validation We have introduced hibernate-validator , So if you introduce spring-boot-starter-web perhaps spring-boot-starter-validation Has been introduced by default hibernate-validator You can stop quoting .

Other versions have not been studied , When you use it, you can study it by yourself .

JSR303 The type of validation defined

 Empty check @Null			 Verify that the object is null@NotNull		 Verify that the object is not null,  Can't check length is 0 String @NotBlank		 Check if the constraint string is Null And the Trim Is the length greater than 0, For strings only , And the space before and after will be removed .@NotEmpty		 Check if the constraint element is NULL Or is it EMPTY. Booelan Check @AssertTrue		 verification  Boolean  Whether the object is  true @AssertFalse	 verification  Boolean  Whether the object is  false  Length check @Size(min=, max=)		 Verify the object (Array,Collection,Map,String) Is the length within the given range  @Length(min=, max=)		 Verify that the element value length of the annotation is min and max Date check in interval @Past		 verification  Date  and  Calendar  Whether the object is before the current time  @Future		 verification  Date  and  Calendar  Whether the object is after the current time  @Pattern	 verification  String  Whether the object conforms to the regular value check of regular expression , It is recommended to use in Stirng,Integer type , It is not recommended to use in int On type , Because the form value is “” Time cannot be converted to int, But it can be converted to Stirng by "",Integer by null@Min			 verification  Number  and  String  Whether the object is large equal to the specified value  @Max			 verification  Number  and  String  Whether the object is small equal to the specified value  @DecimalMax		 The value to be annotated must not be greater than the maximum value specified in the constraint .  The parameter of this constraint is a pass through BigDecimal String representation of the defined maximum value . Decimals have precision @DecimalMin		 The labeled value must be no less than the minimum value specified in the constraint .  The parameter of this constraint is a pass through BigDecimal The string representation of the minimum value defined . Decimals have precision @Digits			 verification  Number  and  String  Whether the constitution of is legal  @Digits(integer=,fraction=)		 Verify that the string is a number in the specified format ,interger Specify integer precision ,fraction Specify decimal precision .@Range(min=, max=)	 Verify that the element value of the annotation is between the minimum value and the maximum value @Range(min=10000,max=50000,message="range.bean.wage")private BigDecimal wage;@Valid  Recursively check the associated objects ,  If the associated object is a collection or an array , Then the elements in it are checked recursively , If it's a map, Then check the value part .( Whether to perform recursive verification )@CreditCardNumber Credit card verification @Email  Verify that it's an email address , If null, No validation , Calculation passed verification .@ScriptAssert(lang= ,script=, alias=)@URL(protocol=,host=, port=,regexp=, flags=)

@Valid and @Validated The difference between

@Valid The note is javax Provided , Follow the standards JSR-303 standard , The package belongs to : javax.validation.Valid

coordination BindingResult It can provide parameter verification results directly .

@Validated yes @Valid A package of , yes Spring The provided verification mechanism uses , follow Spring’s JSR-303 standard ( It's a standard. JSR-303 A variation of ), The package belongs to : org.springframework.validation.annotation.Validated

@Validation Yes @Valid Second encapsulation is carried out , There is no difference in basic usage , But in groups 、 Annotation position 、 Nested verification and other functions are different , Here we mainly explain these situations .

Annotation position

@Validated: Can be used in type 、 Method and method parameters . But it can't be used in member properties ( Field ) On

@Valid: It can be used in methods 、 Constructors 、 Method parameters and member properties ( Field ) On

Can both be used for member properties ( Field ) It directly affects whether nested verification can be provided .

grouping

First define the grouping interface ( Interfaces don't need anything , If it's empty ):

public interface Insert {}
public interface Update {}

In need of verification bean Add a group comment on :

@NotBlank(groups = {Update.class}, message = "ID Can't be empty ")private String id;@NotBlank(groups = {Insert.class, Update.class}, message = " Name cannot be empty ")@Size(groups = {Insert.class, Update.class}, max = 32, message = " The maximum length of the name is 32")private String name;

According to need , stay Controller Add... To the processing request @Validated And introduce the groups that need to be checked ( If no grouping is introduced, it is checked )

@PostMapping("/insert")public int insert(@RequestBody @Validated({Insert.class}) HospitalRequest request) { return hospitalService.insert(request);}@PostMapping("/update")public int update(@RequestBody @Validated({Update.class}) HospitalRequest request) { return h.........

版权声明
本文为[Irving the procedural ape]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012072104511101.html