Use Validation annotation to verify parameters in Spring
In daily development, parameter verification is a common requirement, and Java'sBean ValidationProvides an elegant way to verify the fields of an object by annotation. Spring has deeply integrated this function, making it very simple to implement verification at the Controller, Service and other levels.
This article will introduce how to use Validation annotations in Spring from the following aspects:
- Introduce dependencies
- Simple example
- Classification and description of common verification annotations
- Group verification
- Custom verification
1. Introduce dependencies
Before using the Spring verification function, relevant dependencies need to be introduced.
Hibernate Validator is usually used as an implementation of JSR 380.
Maven
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
Gradle
implementation ':spring-boot-starter-validation'
2. Simple example
The following is a basic parameter verification example. We passed@NotNull
, @Size
etc. Annotations check the parameters and return an error message when the verification fails.
Data Model
import ; import ; public class User { @NotNull(message = "Username cannot be empty") @Size(min = 3, max = 15, message = "The username must be between 3 and 15 characters") private String username; @NotNull(message = "Password cannot be empty") @Size(min = 6, message = "Password length is at least 6 characters") private String password; // Getter & Setter public String getUsername() { return username; } public void setUsername(String username) { = username; } public String getPassword() { return password; } public void setPassword(String password) { = password; } }
Controller
import ; import .*; import ; @RestController @RequestMapping("/users") @Validated public class UserController { @PostMapping("/register") public String register(@RequestBody @Valid User user) { return "User registration successfully:" + (); } }
test
Request Example:
Request Body
{ "username": "john", "password": "123456" }
Response successfully
User registration successfully:john
Error request Body
{ "username": "jo", "password": "" }
Response failed
{ "timestamp": "2024-11-18T12:34:56.789", "status": 400, "error": "Bad Request", "message": "The username must be between 3 and 15 characters; the password cannot be empty" }
3. Classification and description of common verification annotations
General verification
annotation | Function description | Example |
---|---|---|
@NotNull |
Field cannot be empty | @NotNull(message="required") |
@NotBlank |
String is not empty and not blank | @NotBlank(message="Required") |
@NotEmpty |
Collection or array cannot be empty | @NotEmpty |
@Size |
string, set length verification | @Size(min=1, max=10) |
Numerical verification
annotation | Function description | Example |
---|---|---|
@Min |
The value must be greater than or equal to the specified value | @Min(18) |
@Max |
The value must be less than or equal to the specified value | @Max(100) |
@Positive |
The value must be a positive number | @Positive |
@PositiveOrZero |
The value must be positive or zero | @PositiveOrZero |
@Negative |
The value must be negative | @Negative |
String verification
annotation | Function description | Example |
---|---|---|
@Email |
Must be a legal email address | @Email(message="Mailbox format error") |
@Pattern |
Must match regular expressions | @Pattern(regexp="\\d{3}-\\d{3}") |
Date verification
annotation | Function description | Example |
---|---|---|
@Past |
Must be a past date | @Past |
@Future |
Must be a future date | @Future |
@PastOrPresent |
Must be past or current date | @PastOrPresent |
@FutureOrPresent |
Must be a future or current date | @FutureOrPresent |
Validation requires the use of regular expression @Pattern(regexp = "") or custom annotation for directly verifying the date format of JSON. It is recommended to use Jackson's @JsonFormat directly.
4. Group verification
In actual projects, different scenarios may require different verification rules, such as the field requirements may be different when adding and updating. Can be passedGroup verificationaccomplish.
Packet interface
public class Group{ public interface CreateGroup {} public interface UpdateGroup {} }
Data Model
import .*; public class User { @NotNull(message = "User ID cannot be empty", groups = ) private Long id; @NotBlank(message = "Username cannot be empty", groups = ) private String username; @NotBlank(message = "Password cannot be empty", groups = ) private String password; // Getter & Setter }
Controller
import ; import .*; @RestController @RequestMapping("/users") @Validated public class UserController { @PostMapping("/create") public String create(@RequestBody @Validated() User user) { return "Create successfully:" + (); } @PostMapping("/update") public String update(@RequestBody @Validated() User user) { return "Update Successfully:" + (); } }
5. Custom verification
When existing annotations cannot meet the requirements, you can customize the verification annotations.
Custom annotations
import ; import ; import .*; @Documented @Constraint(validatedBy = ) // Associated Verifier@Target() @Retention() public @interface ValidUsername { String message() default "Username Illegal"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Custom checker
import ; import ; public class UsernameValidator implements ConstraintValidator<ValidUsername, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { return value != null && ("^[a-zA-Z0-9]+$"); } }
Use custom annotations
public class User { @ValidUsername private String username; // Getter & Setter }
This is the end of this article about using Validation annotation to verify parameters in Spring. For more relevant Spring Validation verification parameters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!