spring validation

Foreword

Check data is an essential function of an interactive website, the front js check can cover most of the verification responsibilities, such as user name is unique, birthday format, and so commonly used mailbox format check check. However, in order to avoid users to bypass the browser, use the http request of a number of illegal tool data directly to the back-end, server-side data validation is necessary, to prevent dirty data fall into the database, if an illegal mailbox database format appears, also make operation and maintenance personnel headache. I before the insurance product development process, data validation system for more stringent requirements and variability and the pursuit of efficiency, have been used as drools rules engine, which served as validation capabilities. In general application, may be used herein, you will be introduced to the data validation check.
Relationship briefly JSR303 / JSR-349 hibernate validation between the spring validation. JSR303 is a standard, JSR-349 is an upgraded version of it, added some new features, some of the provisions they check verification specification that is annotated, such as @ Null, @ NotNull, @ Pattern, they located javax.validation.constraints package at only provides specification does not provide an implementation. The hibernate validation is the practice of this specification (do not hibernate and the linked database orm framework), he provides a corresponding implementation, and adds some additional checking notes, such as @ Email, @ Length, @ Range, etc., they located org.hibernate.validator.constraints package under. And the spring in order to provide universal convenience to the developer, carried out on the second package hibernate validation, verification display validated bean, you can use a spring or hibernate validation Validation, Validation and another spring characteristic, which is springmvc module added automatic calibration, and the calibration information is encapsulated into a particular class. This is undoubtedly convenient to our web development. This paper describes an automatic check in springmvc the mechanism.
The introduction of dependence
We use maven build springboot demo application to demonstrate.

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

We only need to introduce the spring-boot-starter-web can rely on, to see if his son dependent, can be found in the following dependence:

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

Verify I described before, web module uses hibernate-validation, and databind module also provides a corresponding data binding.
Construction of startup class
No need to add additional notes, a typical startup class

@SpringBootApplication
public class ValidateApp {
public static void main(String[] args) {
SpringApplication.run(ValidateApp.class, args);
}
}

Creating an entity class needs to be verified

class Foo {public
@NotBlank
Private String name;

@min (18 is)
Private Integer Age;

@Pattern (regexp = "^. 1 (. 3 |. 4 |. 5 |. 7 |. 8). 9 \\ {D} $", Message = " phone number format error ")
@NotBlank (the Message =" phone number can not be empty ")
Private String phone;

@email (the Message =" E-mail format error ")
Private String Email;
// getter setter ...

}

Some of the more common use of check notes, it is quite easy to understand, and comment on the name of the field to infer check the contents of each comment contains a message field for a message when the check fails, a special check annotations, such as the Pattern (regular check), you can also add your own regular expressions.
In the check data @Controller


 

FIG springmvc automatic packaging function is provided for us form parameters, a typical add parameter validation controller as follows.

@Controller
public class FooController {

@RequestMapping("/foo")
public String foo(@Validated Foo foo <1>, BindingResult bindingResult <2>) {
if(bindingResult.hasErrors()){
for (FieldError fieldError : bindingResult.getFieldErrors()) {
//...
}
return "fail";
}
return "success";
}

}

Noteworthy:
<1> before @Validated parameters need to add annotations Foo, the need for verification of its spring, the check information will be stored in the subsequent BindingResult. Note that, you must be adjacent, if there are multiple parameters to be verified, the form may be as follows. foo (@Validated Foo foo, BindingResult fooBindingResult, @ Validated Bar bar, BindingResult barBindingResult); i.e., a class corresponding to a parity check result.
<2> will be automatically filled with the check result, the controller can be determined in a particular operation, such as a jump to an error page according to the service logic.
A basic check is complete, summarize what has been provided under the framework of verification:
JSR offers check notes:
@Null annotated element must be null
@NotNull annotated element must not be null
@AssertTrue annotated element must be true
@AssertFalse annotated element must be false
@Min (value) must be annotated element is a number whose value must be greater than the specified minimum
@Max (value) must be annotated element is a number which must be less than the maximum value equal to the specified
@DecimalMin (value) must be annotated element is a number whose value must be greater than the specified minimum
@DecimalMax (value) must be annotated element is a number which must be less than the maximum value equal to the specified
@Size (max =, min =) the size of the element to be annotated in a specified range
@Digits (integer, fraction) annotated element must be a number whose value must be within an acceptable range
@Past annotated element must be a date in the past
@Future annotated element must be a future date
@Pattern (regex =, flag =) annotated element must match the specified regular expression
Hibernate Validator provides validation annotations:
@NotBlank (message =) authentication string is not null, and the length must be greater than 0
@Email annotated element must be the e-mail address
@Length (min =, max =) within the size of the string must be annotated in a specified range
@NotEmpty annotated string must not be null
@Range (min =, max =, message =) elements must be annotated in the range of appropriate



Check experiment

We check entrance to achieve the above conduct a test request:
Visit http: // localhost: 8080 / foo name = xujingfeng & email = 000 & age = 19 can get the following debug information?:


 

Experiment tells us, check the results played a role. And it can be found when multiple errors occur, spring validation does not stop immediately after the first error occurred, but continued trial and error, tell us all wrong. debug can view more rich error information, which are spring convenience features validation provides us with basic for most scenes.
发布了604 篇原创文章 · 获赞 8 · 访问量 1万+

Guess you like

Origin blog.csdn.net/xiaoyaGrace/article/details/104292004