Use javax.validation.constraints to verify the legality of parameters

In the Java development process, data validation is a crucial task. In order to ensure the integrity and correctness of the data, we usually need to perform a series of checks on the input data. javax.validation.constraintsProvides a set of annotation-based verification framework, which allows us to complete data verification work concisely and efficiently. This article will discuss in-depth javax.validation.constraintsthe basic usage and advanced applications to help readers better understand and use this powerful verification framework.

Basic Usage: Common Annotations

javax.validation.constraintsContains a set of basic validation annotations, covering most common data validation scenarios. Let's introduce these basic annotations one by one:

  1. @NotNull : Used to check if the value is null.
  2. @NotEmpty : Used to check whether strings, collections, arrays, etc. are empty or null.
  3. @Size : Used to check whether the number of elements of types such as strings, collections, and arrays is within the specified range.
  4. @Min : Used to check if the value is greater than or equal to the specified minimum value.
  5. @Max : Used to check if the value is less than or equal to the specified maximum value.
  6. @DecimalMin : Used to check whether the value is greater than or equal to the specified minimum value (can be a floating point number).
  7. @DecimalMax : Used to check whether the value is less than or equal to the specified maximum value (can be a floating point number).
  8. @Digits : Used to check whether the value meets the specified integer digits and decimal digits requirements.
  9. @Email : Used to check if the string conforms to the email format.
  10. @Pattern : Used to check if a string matches the specified regular expression.

Here is a simple example showing how to use these basic annotations to validate a user entity class:

import javax.validation.constraints.*;

public class User {
    
    

    @NotNull(message = "ID 不能为空")
    private Long id;

    @NotEmpty(message = "用户名不能为空")
    @Size(min = 2, max = 20, message = "用户名长度必须在 2 到 20 个字符之间")
    private String username;

    @Min(value = 18, message = "年龄必须大于等于 18 岁")
    @Max(value = 100, message = "年龄必须小于等于 100 岁")
    private int age;

    @Email(message = "电子邮件格式不正确")
    private String email;

    // Getter and Setter ...
}

Advanced Application: Custom Annotations and Validators

Although javax.validation.constraintsrich basic annotations are provided, sometimes we need to perform some specific verification operations. At this time, we can implement these requirements through custom annotations and validators.

Here's an example showing how to create a custom annotation @Passwordthat checks that a password meets the strength requirements (contains at least one uppercase letter, one lowercase letter, and one number):

  1. First, create a custom annotation @Password:
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = PasswordValidator.class)
@Target({
    
    ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Password {
    
    

    String message() default "密码必须包含至少一个大写字母、一个小写字母和一个数字";

    Class<?>[] groups() default {
    
    };

    Class<? extends Payload>[] payload() default {
    
    };
}
  1. Then, create a custom validator PasswordValidator:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordValidator implements ConstraintValidator<Password, String> {
    
    

    private static final String PASSWORD_PATTERN = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$";

    @Override
    public void initialize(Password constraintAnnotation) {
    
    
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
    
    
        if (value == null) {
    
    
            return false;
        }
        return value.matches(PASSWORD_PATTERN);
    }
}
  1. Finally, add custom annotations on the fields that need to be validated @Password:
public class User {
    
    

    // ... 其他字段

    @Password
    private String password;

    // Getter and Setter ...
}

Integrate Spring Boot

In the Spring Boot project, we can easily integrate javax.validation.constraintsdata validation. First, you need to add the following dependencies to the project's pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Then, add annotations before the parameters of the Controller method @Validto trigger data verification. When validation fails, Spring Boot throws MethodArgumentNotValidExceptionan exception. We can catch this exception by defining a global exception handler, and return the verification failure information to the client:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleValidationException(MethodArgumentNotValidException exception) {
    
    
        StringBuilder message = new StringBuilder();
        exception.getBindingResult().getFieldErrors().forEach(fieldError ->
                message.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("; ")
        );
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message.toString());
    }
}

The above is javax.validation.constraintsthe basic usage and advanced application. By mastering this powerful verification framework, we can easily implement data verification functions for Java projects, thereby improving the robustness and maintainability of the code.

Guess you like

Origin blog.csdn.net/xindoo/article/details/131386580