How to use custom validators for data validation in SpringMVC

How to use custom validators for data validation in SpringMVC

Introduction

SpringMVC is a Web framework based on the Spring framework, which provides a complete set of MVC architecture, which can help developers quickly build Web applications. In web development, data verification is a very important part, it can help us ensure the validity and integrity of data, and prevent malicious attacks and data leakage.

SpringMVC provides a powerful data validation mechanism, which can easily verify the data submitted by the form. In addition to the built-in validators, SpringMVC also supports custom validators, allowing developers to customize validation rules according to business needs. This article will introduce how to use custom validators in SpringMVC.

insert image description here

SpringMVC data verification mechanism

The data validation mechanism of SpringMVC is based on the JSR 303 specification, which is the Bean Validation specification. This specification defines a set of standard annotations for describing data validation rules. SpringMVC provides a unified validator interface Validatorfor performing data validation. Developers can implement this interface and write custom validators.

In SpringMVC, data validation happens before controller methods are executed. When form data is submitted to a controller method, SpringMVC automatically converts the form data into Java objects and performs data validation. If the verification fails, org.springframework.validation.BindExceptionan exception will be thrown, and the developer can handle the exception in the exception handler.

custom validator

A custom validator refers to a validator written by a developer based on business requirements. In SpringMVC, a custom validator needs to implement Validatorthe interface and override supports()the and validate()methods.

supports()method

supports()Method is used to determine whether the current validator supports a certain validation object. The parameter of this method is an Classobject, indicating the type of object to be verified. Developers need to judge whether the type meets the requirements of the validator in this method, and return it if it does, trueotherwise return it false.

public class MyValidator implements Validator {
    
    
    @Override
    public boolean supports(Class<?> clazz) {
    
    
        // 判断 clazz 是否是待验证对象的类型
        // 如果是,则返回 true,否则返回 false
    }
}

validate()method

validate()method is used to perform data validation. There are two parameters of this method, which are the object to be verified and Errorsthe object. ErrorsObject is used to save validation error information. Developers need to write verification logic in this method, and save the verification results to Errorsthe object.

public class MyValidator implements Validator {
    
    
    @Override
    public void validate(Object target, Errors errors) {
    
    
        // 编写验证逻辑
        // 如果验证失败,则调用 errors.reject() 方法保存错误信息
    }
}

Using custom validators in SpringMVC

The steps to use a custom validator are as follows:

  1. Define the object to be verified
  2. Write a custom validator
  3. Inject custom validators in controller methods
  4. Perform data validation

Define the object to be verified

The object to be verified refers to the Java object corresponding to the data submitted by the form. When defining this object, you need to use the annotations of the Bean Validation specification to describe the validation rules. For example, here is a simple validation object:

public class User {
    
    
    @NotNull
    private String username;
    
    @Size(min = 6, max = 20)
    private String password;
    
    // 省略 getter 和 setter 方法
}

In the above code, usernamethe attribute uses @NotNullannotations, indicating that the attribute cannot be empty; passwordthe attribute uses @Sizeannotations, indicating that the length of the attribute must be between 6 and 20.

Write a custom validator

The steps of writing a custom validator have been introduced earlier, so I won't go into details here.

Inject custom validators in controller methods

In controller methods, @InitBindercustom validators need to be registered using annotations. For example, here's a simple controller method:

@PostMapping("/register")
public String register(@Valid User user, BindingResult result) {
    
    
    if (result.hasErrors()) {
    
    
        // 处理验证错误
    }
    // 处理注册逻辑
}

In the above code, @Validthe annotation means to Userperform data validation on the object, and BindingResultthe object is used to save the validation error information. BindingResultIf validation fails, error information can be obtained in the object.

In order to use a custom validator, you need to add an annotation to the controller @InitBinderand register the custom validator with that annotation. For example, here's a simple custom validator and controller method:

public class MyValidator 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.getPassword().equals(user.getConfirmPassword())) {
    
    
            errors.rejectValue("confirmPassword", "password.not.match");
        }
    }
}

@Controller
public class UserController {
    
    
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    
    
        binder.addValidators(new MyValidator());
    }

    @PostMapping("/register")
    public String register(@Valid User user, BindingResult result) {
    
    
        if (result.hasErrors()) {
    
    
            // 处理验证错误
        }
        // 处理注册逻辑
    }
}

In the above code, MyValidatorthe class implements a custom validator, which verifies whether the password entered by the user is consistent with the confirmation password. In the controller, use @InitBinderthe annotation to register the custom validator, and then use @Validthe annotation to perform data validation on Userthe object in the controller method.

Summarize

SpringMVC provides a powerful data validation mechanism, which can easily verify the data submitted by the form. In addition to the built-in validators, SpringMVC also supports custom validators, allowing developers to customize validation rules according to business needs. This article introduces how to use custom validators in SpringMVC, including steps such as defining objects to be validated, writing custom validators, and injecting custom validators into controller methods. Developers can write custom validators according to their own business needs to ensure the validity and integrity of data and improve the security and stability of web applications.

Guess you like

Origin blog.csdn.net/2302_77835532/article/details/131677762