When developing web applications, data verification is a part that cannot be ignored. Whether it is registering user information, submitting form data, or processing business logic, the validity and integrity of the data need to be guaranteed. Spring Boot provides powerful verification functions based onHibernate ValidatorThe framework simplifies the implementation of data verification through annotation. This article will introduce Spring Boot's Validation interface verification mechanism in detail, including its core functions, common annotations, custom verification, and practical application scenarios.
1. What is Spring Validation?
Spring Validation is a framework for data verification, based onJSR-303(Bean Validation API)andHibernate Validatoraccomplish. By adding specific annotations to the fields of JavaBeans, you can define the verification rules for the data. Spring Boot makes it easier to use data verification in web applications by integrating Hibernate Validator.
2. The core features of Spring Boot Validation
- Annotation verification: Define data verification rules through annotations.
- Automatic verification: Spring Boot provides automatic support for verification without manually writing verification logic.
- Exception handling: Spring Boot can automatically return the error message of verification failure to the client.
- Support group verification: Different verification packets can be defined for different scenarios.
- Supports custom verification: You can extend the annotations and define custom verification logic.
3. Commonly used verification annotations
The following are commonly used verification annotations in Spring Boot:
annotation | Function description |
---|---|
@NotNull |
Make sure the field is not null |
@Null |
Make sure the field is null |
@NotBlank |
Make sure the field is not empty (string) |
@NotEmpty |
Make sure that the fields are not empty (collection, array) |
@Length |
Make sure the length of the field is within the specified range |
@Size |
Ensure that the length of the field is within the specified range (applicable to collections, arrays, strings) |
@Range |
Make sure that the value of the field is within the specified range |
@Min |
Make sure that the value of the field is greater than or equal to the specified value |
@Max |
Make sure that the value of the field is less than or equal to the specified value |
@Email |
Make sure the field is a valid email address |
@Pattern |
Make sure that the value of the field matches the specified regular expression |
@Past |
Make sure the value of the field is a past date |
@Future |
Make sure that the value of the field is a future date |
4. Implementation steps of Spring Boot Validation
Step 1: Add dependencies
existAdd the following dependencies to the file:
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
Step 2: Create a JavaBean
Create a JavaBean class that needs verification and add verification annotations to the fields:
import .*; public class User { @NotNull(message = "Username cannot be empty") @Size(min = 2, max = 10, message = "The username must be between 2 and 10") private String username; @NotNull(message = "Password cannot be empty") @NotBlank(message = "Password cannot be empty") @Pattern(regexp = "^(?=.*\\d)(?=.*[A-Za-z])(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]{8,20}$", message = "Password format is incorrect") private String password; @Email(message = "The email format is incorrect") private String email; @Min(value = 18, message = "Age must be greater than or equal to 18 years old") private Integer age; public User() {} // Getters and Setters }
Step 3: Use @Valid annotation in the controller
Use in the parameters of the controller@Valid
Annotation enables verification:
import ; import ; import ; import ; import ; import ; @RestController public class UserController { @PostMapping("/register") public ResponseEntity<?> register(@Valid @RequestBody User user) { // Business logic return ("Registered successfully"); } }
Step 4: Handle the verification exception
Spring Boot will automatically encapsulate the error message that failed to check intoMethodArgumentNotValidException
Exception is in progress. The error message can be returned uniformly through global exception handling:
import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler() public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = (); (fieldName, errorMessage); }); return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } }
5. Custom verification annotations
If the built-in verification annotation cannot meet the needs, you can extend the verification function by customizing the comments.
Custom verification annotations
import ; import ; import ; import ; import ; import ; import ; @Documented @Constraint(validatedBy = {}) @Target({}) @Retention() public @interface Phone { String message() default "Mobile phone number format is incorrect"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Custom verification logic
import ; import ; public class PhoneValidator implements ConstraintValidator<Phone, String> { @Override public void initialize(Phone constraintAnnotation) { } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return false; } // Mobile phone number regular expression String regex = "^1(3\\d|5[i-o]\\d|78\\d|4\\d)\\d{7}$"; return (regex); } }
Use custom verification annotations
@Phone(message = "Mobile phone number format is incorrect") private String phone;
6. Group checksum condition verification
Group verification
Through group verification, different verification rules can be defined for different scenarios.
public interface SaveGroup { } public interface UpdateGroup { } @NotNull(groups = ) @Size(min = 2, max = 10, groups = {, }) private String username;
Specify the grouping to be checked in the controller:
@PostMapping("/save") public ResponseEntity<?> save(@Validated() @RequestBody User user) { // Business logic return ("Save successfully"); }
Condition verification
pass@ScriptAssert
Annotation, complex conditional verification can be implemented based on scripting languages (such as JavaScript or Groovy).
@ScriptAssert(lang = "javascript", script = " >= 8 && (/^(?=.*\\d)(?=.*[A-Za-z])(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]{8,20}$/)") public class User { // Field definition}
7. Combined with other technologies
1. Unified exception handling
Through global exception handling, the error message of verification failed can be returned uniformly to improve the user experience.
2. Logging
Through AOP (Aspect Oriented Programming), you can record the log of verification failure, which facilitates subsequent analysis:
@Aspect @Component public class ValidationAspect { @Around("execution(* *(..)) && @annotation()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { try { Object[] args = (); if (args != null && > 0) { for (Object arg : args) { if (arg != null && ().getAnnotation() != null) { // Logging ("Start checking data:" + arg); } } } return (); } catch (MethodArgumentNotValidException ex) { // Record the log of verification failed ("Check failed:" + ()); throw ex; } } }
8. FAQs and Solutions
Frequently Asked Questions
-
Verification annotation does not take effect:
- Check if it has been added
spring-boot-starter-validation
Dependence. - Make sure it is used in the controller
@Valid
Annotation.
- Check if it has been added
-
Error message does not return:
- Check whether global exception handling is implemented.
- Make sure the controller's return type is
ResponseEntity
。
-
Custom verification annotations do not take effect:
- Check custom annotations
ConstraintValidator
Whether it is implemented correctly. - Make sure that custom annotations are used
@Constraint
Annotation.
- Check custom annotations
Summarize
Spring Boot's Validation function provides a simple and powerful data verification method. Through annotated checksum automation processing, it can significantly improve development efficiency and code quality. CombinedHibernate ValidatorWith the powerful functions of , developers can easily implement complex verification logic, and meet different business needs through custom verification annotations and group verification.
I hope this article can help you better use Spring Boot's Validation feature in real projects, improving the robustness and user experience of your code!
This is the end of this article about the detailed process of Spring Boot Validation interface verification from zero. For more related Spring Boot Validation interface verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!