A detailed introduction to the parameter validation @Validation annotation in Spring

In the Spring framework, @Validannotations are a powerful tool for verifying and verifying data entered by users to ensure the legality and integrity of data. By combining with other annotations and validators, @Validannotations can easily implement data validation, thus improving the robustness and security of the application. This article will detail annotations in Spring @Validand how to use it correctly in your application.

What are @Validannotations?

@ValidAnnotation is an annotation in the Spring framework, which is used to mark the target of data validation on method parameters or method return values. It tells Spring to perform data validation when processing method calls. This annotation is usually used in combination with other validation-related annotations, such as @NotNull, @NotBlank, @Min, @Maxetc., to specify validation rules.

Method parameter validation using @Validannotations

Using annotations on method parameters @Valid, parameters can be validated before method invocation. This is useful for ensuring the validity of input data.

Here is an example showing how to use @Validannotations for parameter validation in Spring controller methods:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    
    

    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@Valid @RequestBody UserDto userDto) {
    
    
        // 处理用户注册逻辑
        return ResponseEntity.ok("User registered successfully");
    }
}

In the example above, @Validthe annotation is used userDtoon the parameter. Spring will validate the properties of the parameter registerUserbefore calling the method .userDto

Combined with other validation annotations

Typically, @Validannotations are used in conjunction with other validation-related annotations to define validation rules. For example, you can use annotations such as @NotNull, @NotBlank, @Min, @Maxetc. to perform more specific validation on attributes.

public class UserDto {
    
    

    @NotNull
    @NotBlank
    private String username;

    @NotNull
    @Min(18)
    private Integer age;

    // ...其他属性和方法
}

In the example above, usernamethe attribute is annotated with @NotNulland @NotBlank, indicating that it cannot be empty and cannot contain only spaces. ageThe attribute is annotated with @NotNulland @Min(18), indicating that it cannot be empty and must be greater than or equal to 18.
In the Spring framework, you can use various validation annotations to define different types of validation rules. These annotations are located javax.validation.constraintsunder the package and are used to validate different aspects of the data. The following are some common validation annotations and their corresponding validation rules:

  1. @NotNull: Validation field cannot be null.

  2. @NotBlank: The verification string cannot be empty and contains at least one non-null character.

  3. @NotEmpty: Unlike Validating that a string, collection, or array cannot be empty, @NotBlankit does not require at least one non-null character.

  4. @Min(value): The validation number must be greater than or equal to the specified minimum.

  5. @Max(value): The validation number must be less than or equal to the specified maximum value.

  6. @Size(max, min): Validates that the size of a string, collection, or array must be within the specified range.

  7. @Email: Verify that the string is a valid email address.

  8. @Pattern(regexp): Verify that the string matches the specified regular expression.

  9. @Digits(integer, fraction): Validates that a number meets the specified number of digits, including integer and fractional parts.

  10. @Positive: Validation number must be positive.

  11. @Negative: Validation number must be negative.

  12. @Past: Validation date must be in the past.

  13. @Future: Validation date must be in the future.

  14. @AssertTrue: The validation field must be true.

  15. @AssertFalse: The validation field must be false.

  16. @CreditCardNumber: Verify that the string is a valid credit card number.

  17. @URL: Verify whether the string is a legal URL.

  18. @Valid: Used to mark objects that require nested validation.

These are just some common validation annotations, in fact there are many more validation annotations available in Spring. You can choose appropriate validation annotations to define data validation rules based on specific business needs. In addition, you can also implement more complex validation logic by custom validators to meet specific validation requirements.

custom validator

In addition to using predefined validation annotations, you can also create custom validators to meet specific validation needs. To create a custom validator, implement javax.validation.ConstraintValidatorthe interface.

Here is an example showing how to create a custom validator:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class AgeConstraintValidator implements ConstraintValidator<AgeConstraint, Integer> {
    
    

    @Override
    public boolean isValid(Integer age, ConstraintValidatorContext context) {
    
    
        return age != null && age >= 18;
    }
}

Then, you can use this validator on custom annotations:

import javax.validation.Constraint;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({
    
    FIELD, METHOD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = AgeConstraintValidator.class)
public @interface AgeConstraint {
    
    
    String message() default "Invalid age";
    Class<?>[] groups() default {
    
    };
    Class<? extends Payload>[] payload() default {
    
    };
}

Finally, apply this custom annotation to the properties that need to be validated:

public class UserDto {
    
    

    @NotNull
    @NotBlank
    private String username;

    @AgeConstraint
    private Integer age;

    // ...其他属性和方法
}

Summarize

@ValidAnnotations are an important tool in the Spring framework for data validation and verification. Combined with other validation annotations and custom validators, it can

Easily validate user-entered data, improving application stability and security. By adding annotations to method parameters or method return values @Valid, you can ensure the validity of the data and generate corresponding error messages when the data is invalid, thereby providing better user experience and data integrity.

Guess you like

Origin blog.csdn.net/weixin_42279822/article/details/132188717