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.
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 Validator
for 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.BindException
an 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 Validator
the 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 Class
object, 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, true
otherwise 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 Errors
the object. Errors
Object is used to save validation error information. Developers need to write verification logic in this method, and save the verification results to Errors
the 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:
- Define the object to be verified
- Write a custom validator
- Inject custom validators in controller methods
- 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, username
the attribute uses @NotNull
annotations, indicating that the attribute cannot be empty; password
the attribute uses @Size
annotations, 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, @InitBinder
custom 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, @Valid
the annotation means to User
perform data validation on the object, and BindingResult
the object is used to save the validation error information. BindingResult
If 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 @InitBinder
and 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, MyValidator
the class implements a custom validator, which verifies whether the password entered by the user is consistent with the confirmation password. In the controller, use @InitBinder
the annotation to register the custom validator, and then use @Valid
the annotation to perform data validation on User
the 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.