Lesson 2-1: Spring Boot's support for basic Web development (part 2)

We continue to explain the content of the previous lesson.

Data validation

In many cases, when we are dealing with the business logic of an application, data verification is something that must be considered and faced. The application must use some means to ensure that the input data is semantically correct. In Java applications, the input data must be semantically analyzed to be effective, that is, data verification.

Input verification is one of the most important Web development tasks. There are two ways to verify input in Spring MVC: one is the verification framework that comes with Spring, and the other is to use JSR.

JSR is a specification document that specifies a set of APIs and adds constraints to object properties through annotations. Hibernate Validator is the specific implementation of the JSR specification. Hibernate Validator provides the implementation of all built-in constraint annotations in the JSR specification, as well as some additional constraint annotations. In addition, users can also customize the constraint annotations.

The parameter verification of Spring Boot relies on hibernate-validator. To use Hibernate Validator to verify data, you need to define a received data model, and use annotations to describe the rules of field verification. We take the User object as an example to show you how to use it.

First, add a save method saveUser in WebController, the parameter is User.

@RequestMapping("/saveUser")
public void saveUser(@Valid User user,BindingResult result) {
    System.out.println("user:"+user);
    if(result.hasErrors()) {
        List<ObjectError> list = result.getAllErrors();
        for (ObjectError 

Guess you like

Origin blog.csdn.net/ityouknow/article/details/108729172