Overview
In Java, data verification usually relies on the Bean Validation API, especially the Jakarta Bean Validation (formerly Hibernate Validator). This API allows you to define and execute constraint rules on Java objects to ensure the validity and consistency of the data. The following is relatedDetailed explanation of its related dependencies:
1. Dependency package
For projects using the Bean Validation API, it is usually necessary to add relevant dependencies. Taking Maven as an example, it usually includes the following main dependencies:
Jakarta Bean Validation API
This is the API specification definition package of Bean Validation, which defines the basic interface and annotations for data verification.
<dependency> <groupId></groupId> <artifactId>-api</artifactId> <version>3.0.2</version> <!-- Version may change --> </dependency>
Hibernate Validator
This is an implementation of Bean Validation, providing a specific implementation of the API.
<dependency> <groupId></groupId> <artifactId>hibernate-validator</artifactId> <version>8.0.</version> <!-- Version may change --> </dependency>
EL (Expression Language) Implementation
Hibernate Validator may require an EL implementation to handle some annotated expressions.
<dependency> <groupId></groupId> <artifactId></artifactId> <version>3.0.0</version> <!-- Version may change --> </dependency>
2. Main annotations and their functions
The following isA detailed explanation of some core annotations in the package:
@NotNull
-
Function: Make sure the value is not
null
。 - usage:
@NotNull private String name;
@Size
- Function: Verify the length of a string, collection, or array.
-
property:
-
min
: Minimum length -
max
: Maximum length
-
- usage:
@Size(min = 2, max = 30) private String username;
@Min and @Max
- Function: Used to set the minimum and maximum values of the numeric value.
-
property:
-
value
: Minimum value (@Min
) or maximum value (@Max
)
-
- usage:
@Min(18) private int age; @Max(120) private int age;
- Function: Verify that the string conforms to the email format.
- usage:
@Email private String email;
@Pattern
- Function: Verify that the string complies with the regular expression pattern.
-
property:
-
regexp
: Regular expression
-
- usage:
@Pattern(regexp = "\\d{10}") private String phoneNumber;
@Positive and @Negative
- Function: Verify whether the value is a positive or negative number.
- usage:
@Positive private int positiveNumber; @Negative private int negativeNumber;
@Past and @Future
-
Function:
@Past
Verify that the date is before the current date,@Future
Verify that the date is after the current date. - usage:
@Past private LocalDate birthDate; @Future private LocalDate expiryDate;
3. How to use
Configuring and using Validator
Using the Bean Validation API usually involves the following steps:
1. Create and configure ValidatorFactory:
ValidatorFactory factory = (); Validator validator = ();
2. Verification object:
User user = new User(); ("A"); (17); Set<ConstraintViolation<User>> violations = (user); for (ConstraintViolation<User> violation : violations) { (()); }
3. Use Spring Boot Integration:
In Spring Boot app,and
spring-boot-starter-validation
Automatic integration. Spring Boot automatically handles verification of Java Beans with annotations.
Example:
Java Bean:
import ; import ; import ; import ; public class User { @NotNull(message = "Username cannot be null") @Size(min = 2, max = 30, message = "Username must be between 2 and 30 characters") private String username; @NotNull(message = "Age cannot be null") @Min(value = 18, message = "Age must be at least 18") private Integer age; @Email(message = "Email should be valid") private String email; // Getters and Setters }
Controller:
import ; import ; import ; import ; import ; @RestController public class UserController { @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { // Handle valid user return ("User is valid!"); } }
In this example, Spring Boot automatically verifies the request body
User
object and return the corresponding verification error message (if any).
4. Customize verification logic
You can also customize the verification logic by implementingConstraintValidator
Interface to create custom annotations.
Example:
Custom annotations:
import ; import ; import ; import ; import ; import ; @Constraint(validatedBy = ) @Target({ , }) @Retention() public @interface CustomConstraint { String message() default "Custom validation failed"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Custom Verifier:
import ; import ; public class CustomValidator implements ConstraintValidator<CustomConstraint, String> { @Override public void initialize(CustomConstraint constraintAnnotation) {} @Override public boolean isValid(String value, ConstraintValidatorContext context) { // Custom verification logic return value != null && () > 5; } }
Apply custom annotations:
public class Example { @CustomConstraint private String customField; }
Summarize
Packages and their implementations such as Hibernate Validator provide a powerful data verification framework that can effectively ensure the validity of data in Java applications. With annotations, interfaces, and custom verification logic, you can flexibly implement data verification and integrate with frameworks such as Spring Boot to improve application robustness and user experience.
This is the article about the explanation of several main dependency packages for data verification in Java. For more related contents of Java data verification, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!