How to use @Valid annotation for data validation in SpringMVC

How to use @Valid annotation for data validation in SpringMVC

In web development, data validation is a very important part. It can ensure the legality and correctness of data, and protect the system from malicious attacks or user misoperations. In SpringMVC, we can use the @Valid annotation to implement data validation.

insert image description here

The role of @Valid annotation

The @Valid annotation is an annotation in the javax.validation package, which can be used to mark data objects that need to be validated. When an object annotated with @Valid is passed to a SpringMVC controller method, SpringMVC will automatically call the validator to validate the object.

Data Verification Process

The data validation process in SpringMVC is as follows:

  1. The client initiates the request.
  2. After receiving the request, DispatcherServlet maps to the corresponding Controller according to the requested URL.
  3. After the method in the Controller receives the request, if there is data that needs to be verified, it is marked with the @Valid annotation.
  4. If the data validation fails, a MethodArgumentNotValidException will be thrown, and SpringMVC will automatically encapsulate the error information in JSON format and return it to the client.
  5. If the data validation passes, the Controller method continues execution.

How to use the @Valid annotation

In SpringMVC, we can use the @Valid annotation in the parameters of the Controller method to mark the data objects that need to be validated. For example:

@RequestMapping("/user")
public String addUser(@Valid User user, BindingResult result) {
    
    
    if (result.hasErrors()) {
    
    
        // 处理验证失败的情况
    }
    // 处理验证成功的情况
}

In the above example, we use the @Valid annotation to annotate the User object. When this object is passed to the addUser method, SpringMVC will automatically call the validator to verify the object. The verification result will be encapsulated into a BindingResult object, through which we can obtain the verification result.

Rules for Data Validation

When using the @Valid annotation for data validation, we need to define validation rules. Validation rules can be implemented by adding annotations in the javax.validation.constraints package to the corresponding data objects. For example, we can add the following annotations to the User class:

public class User {
    
    
    @NotNull(message = "用户名不能为空")
    private String username;
    
    @Size(min = 6, max = 20, message = "密码长度必须在 6 到 20 个字符之间")
    private String password;
    
    @Email(message = "邮箱格式不正确")
    private String email;
    // 省略 getter 和 setter 方法
}

In the above example, we use @NotNull, @Size and @Email annotations to define the validation rules for username, password and email. If these rules are violated, the validator will automatically encapsulate the error information into a BindingResult object and return it to the client.

custom validation rules

In addition to using annotations in the javax.validation.constraints package to define validation rules, we can also customize validation rules. Custom validation rules need to implement the ConstraintValidator interface, for example:

public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {
    
    
    private CaseMode caseMode;
    
    @Override
    public void initialize(CheckCase constraintAnnotation) {
    
    
        this.caseMode = constraintAnnotation.value();
    }
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
    
    
        if (value == null) {
    
    
            return true;
        }
        
        if (caseMode == CaseMode.UPPER) {
    
    
            return value.equals(value.toUpperCase());
        } else {
    
    
            return value.equals(value.toLowerCase());
        }
    }
}

In the above example, we implemented a CheckCaseValidator validator, which can be used to verify whether a string is all uppercase or all lowercase. This validator needs to be annotated with the @CheckCase annotation, for example:

public class User {
    
    
    @CheckCase(CaseMode.UPPER)
    private String name;
    // 省略 getter 和 setter 方法
}

Summarize

In this article, we introduced data validation in SpringMVC and how to use the @Valid annotation to implement data validation. We also covered how to define validation rules and how to customize validation rules. Data verification is a very important part of web development. It can ensure the legality and correctness of data, and protect the system from malicious attacks or user misoperations. Using the @Valid annotation can help us simplify the data validation process, improve development efficiency and code readability.

Guess you like

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