What is the data binding and validation mechanism in Spring MVC and how to use it

In Spring MVC applications, data binding and verification are very important parts. They can help us bind user-submitted data to Java objects and verify the data to ensure the correctness and reliability of the data. In Spring MVC, data binding and validation mechanisms are implemented through annotations. This article will introduce the data binding and validation mechanisms in Spring MVC and how to use them.

Insert image description here

data binding

Data binding is the process of binding user-submitted data to Java objects. In Spring MVC, data binding is achieved through the @ModelAttribute annotation.

@ModelAttribute annotation

The @ModelAttribute annotation is used to bind request parameters to Java objects. It can be used on method parameters or method return values.

When the @ModelAttribute annotation is used on the parameters of a method, it indicates that the request parameters are bound to the parameters of the method. For example:

@GetMapping("/user")
public String getUser(@ModelAttribute("id") Long id) {
    
    
    // ...
}

In this example, the @ModelAttribute("id") annotation indicates that the parameter named id in the HTTP request parameter is bound to the id parameter of the method.

When the @ModelAttribute annotation is used on the return value of a method, it means that the return value of the method is added to the model. For example:

@ModelAttribute("user")
public User getUser(@RequestParam("id") Long id) {
    
    
    User user = userRepository.findById(id).orElse(null);
    return user;
}

In this example, the @ModelAttribute(“user”) annotation adds the return value of the getUser method to the model and references it in the view using a variable named user.

Data type conversion

When binding request parameters to a Java object, Spring MVC automatically converts them based on the type of the Java object. For example, when binding a request parameter to an Integer type property, Spring MVC will automatically convert the string type request parameter into an Integer type.

If the type of the request parameter does not match the type of the Java object, or if the request parameter is not in the correct format, data binding will fail. At this time, Spring MVC will throw an exception and return the exception information to the client.

Use of data binding

Data binding can help us bind user-submitted data to Java objects, simplifying code writing. When using data binding, we need to define a Java object to store user-submitted data. We can then use the @ModelAttribute annotation to bind the request parameters to the Java object, and then use the Java object in the controller to process the user-submitted data.

For example, we define a User class to store user-submitted data:

public class User {
    
    
    private Long id;

    private String name;

    private Integer age;

    // getters and setters
}

Then, we use the @ModelAttribute annotation in the controller to bind the request parameters to the User object:

@PostMapping("/user")
public String saveUser(@ModelAttribute("user") User user) {
    
    
    // ...
}

In this example, the @ModelAttribute("user") annotation indicates that the request parameters are bound to the User object named user.

data verification

Data verification is to verify the data submitted by users to ensure the correctness and reliability of the data. In Spring MVC, data validation is implemented through @Valid annotation and validator (Validator).

@Valid annotation

The @Valid annotation is used to enable data validation. It can be used on method parameters or method return values.

When the @Valid annotation is used on the parameters of a method, it indicates data validation of the method parameters. For example:

@PostMapping("/user")
public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
    
    
    // ...
}

In this example, the @Valid annotation represents data validation on the User object bound to the @ModelAttribute("user") annotation.

When the @Valid annotation is used on the return value of a method, it indicates data validation on the return value of the method. For example:

@PostMapping("/user")
@Validated
public String saveUser(@ModelAttribute("user") User user) {
    
    
    // ...
}

In this example, the @Validated annotation represents data validation on the return value of the saveUser method.

Validator

A validator is a component used to validate data based on its format or business rules. In Spring MVC, validators are implemented by implementing the Validator interface.

The Validator interface defines two methods:

  • supports(Class<?> clazz): Used to determine whether the validator supports the specified data type.
  • validate(Object target, Errors errors): Used to validate the target object and save the validation results in the Errors object.

We can implement the Validator interface and write our own validator. For example, we define a UserValidator class to verify whether the User object meets the requirements:

@Component
public class UserValidator implements Validator {
    
    
    @Override
    public boolean supports(Class<?> clazz) {
    
    
        return User.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
    
    
        User user = (User) target;
        if (user.getName() == null || user.getName().isEmpty()) {
    
    
            errors.rejectValue("name", "user.name.required", "Name is required");
        }
        if (user.getAge() != null && user.getAge() < 0) {
    
    
            errors.rejectValue("age", "user.age.invalid", "Age is invalid");
        }
    }
}

In this example, the UserValidator class implements the Validator interface and overrides the supports() and validate() methods. The supports() method is used to determine whether the validator supports User type data, and the validate() method is used to validate the User object and save the validation results in the Errors object.

Use of data validation

Data validation can help us ensure the correctness and reliability of data submitted by users and improve the robustness and reliability of the system. When using data validation, we need to define a validator to validate the data submitted by the user. We can then enable data validation using the @Valid annotation and use the BindingResult object in the controller to obtain the validation results.

For example, we define a UserValidator class for validating User objects:

@Component
public class UserValidator implements Validator {
    
    
    @Override
    public boolean supports(Class<?> clazz) {
    
    
        return User.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
    
    
        User user = (User) target;
        if (user.getName() == null || user.getName().isEmpty()) {
    
    
            errors.rejectValue("name", "user.name.required", "Name is required");
        }
        if (user.getAge() != null && user.getAge() < 0) {
    
    
            errors.rejectValue("age", "user.age.invalid", "Age is invalid");
        }
    }
}

Then, use the @Valid annotation in the controller to enable data validation and use the BindingResult object to obtain the validation result:

@PostMapping("/user")
public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
    
    
    if (result.hasErrors()) {
    
    
        // 处理验证错误
    } else {
    
    
        // 保存用户数据
    }
}

In this example, the @Valid annotation means enabling the data validation function, the @ModelAttribute("user") annotation means binding the request parameters to the User object, and the BindingResult object is used to obtain the verification result.

Summarize

This article introduces the data binding and validation mechanism in Spring MVC. Data binding is the process of binding user-submitted data to Java objects, which can be achieved using the @ModelAttribute annotation. Data validation is to verify the data submitted by the user, which can be achieved using @Valid annotation and validator. Data binding and validation can help us simplify code writing and improve the robustness and reliability of the system.

Guess you like

Origin blog.csdn.net/JasonXu94/article/details/131626082