12

使用javax.validation.constraints校验参数合法性

 2 years ago
source link: https://zxs.io/article/1929
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在Java开发过程中,数据校验是一项至关重要的任务。为了确保数据的完整性和正确性,我们通常需要对输入的数据进行一系列的校验。javax.validation.constraints提供了一套基于注解的校验框架,能够让我们简洁、高效地完成数据校验工作。本文将深入探讨javax.validation.constraints的基本用法和高级应用,帮助读者更好地理解和运用这个强大的校验框架。

基本用法:常用注解

javax.validation.constraints包含了一组基础的校验注解,覆盖了大多数常见的数据校验场景。下面我们逐一介绍这些基本注解:

  1. @NotNull: 用于检查值是否为null。
  2. @NotEmpty: 用于检查字符串、集合、数组等类型是否为空或null。
  3. @Size: 用于检查字符串、集合、数组等类型的元素个数是否在指定的范围内。
  4. @Min: 用于检查数值是否大于等于指定的最小值。
  5. @Max: 用于检查数值是否小于等于指定的最大值。
  6. @DecimalMin: 用于检查数值是否大于等于指定的最小值(可以是浮点数)。
  7. @DecimalMax: 用于检查数值是否小于等于指定的最大值(可以是浮点数)。
  8. @Digits: 用于检查数值是否符合指定的整数位数和小数位数要求。
  9. @Email: 用于检查字符串是否符合电子邮件格式。
  10. @Pattern: 用于检查字符串是否符合指定的正则表达式。

以下是一个简单的示例,展示了如何使用这些基本注解对一个用户实体类进行校验:

复制
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 ...
}

高级应用:自定义注解和校验器

尽管javax.validation.constraints提供了丰富的基础注解,但有时我们还需要进行一些特定的校验操作。这时,我们可以通过自定义注解和校验器来实现这些需求。

以下是一个示例,展示了如何创建一个自定义注解@Password,用于检查密码是否符合强度要求(至少包含一个大写字母、一个小写字母和一个数字):

  1. 首先,创建自定义注解@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. 然后,创建自定义校验器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. 最后,在需要校验的字段上添加自定义注解@Password
复制
public class User {

    // ... 其他字段

    @Password
    private String password;

    // Getter and Setter ...
}

整合Spring Boot

在Spring Boot项目中,我们可以很方便地整合javax.validation.constraints进行数据校验。首先,需要在项目的pom.xml文件中添加以下依赖:

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

然后,在Controller方法的参数前添加@Valid注解,即可触发数据校验。当校验失败时,Spring Boot会抛出MethodArgumentNotValidException异常。我们可以通过定义全局异常处理器来捕获该异常,并将校验失败的信息返回给客户端:

复制
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());
    }
}

以上就是javax.validation.constraints的基本用法和高级应用。通过掌握这个强大的校验框架,我们可以轻松地为Java项目实现数据校验功能,从而提高代码的健壮性和可维护性。

</article


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK