Home >
Java >
javaTutorial >
How to use the SpringBoot parameter verification Validator framework
How to use the SpringBoot parameter verification Validator framework
WBOY
Release: 2023-05-22 23:28:19
forward
1685 people have browsed it
How SpringBoot performs parameter verification
In daily interface development, in order to prevent illegal parameters from affecting the business, it is often necessary to verify the parameters of the interface. For example, the user name needs to be verified when logging in. Check whether the password is empty. When creating a user, you need to verify whether the email and mobile phone number formats are accurate. It would be too cumbersome to rely on code to verify interface parameters one by one, and the readability of the code would be extremely poor.
Validator framework is designed to solve the problem that developers can write less code during development and improve development efficiency; Validator is specially used to verify interface parameters, such as common required verification, email Format verification, the user name must be between 6 and 12, etc...
Validator verification framework follows the JSR-303 verification specification (parameter verification specification), JSR isJava Abbreviation for Specification Requests.
Note: Starting from springboot-2.3 , the verification package is independent into a starter component, so validation and web need to be introduced, while versions before springboot-2.3 only need to introduce web dependencies.
Annotation
Function
##@AssertFalse
can be null, If it is not null, it must be false
@AssertTrue
can be null, if it is not null, it must be true
@DecimalMax
The setting cannot exceed the maximum value
@DecimalMin
The setting cannot exceed the minimum value
@Digits
The setting must be a number and the number of digits in the integer and the number of decimal digits must be within the specified range
@Future
The date must be in the future of the current date
@Past
The date must be in the past of the current date
@Max
The maximum value shall not exceed this maximum value
@Min
The maximum value shall not be less than this minimum value
@NotNull
cannot be null, can be empty
@Null
must be null
##@Pattern
Must satisfy the specified regular expression
@Size
The size() value of collections, arrays, maps, etc. must be within the specified range
@Email
Must be in email format
@Length
The length must be within the specified range
@NotBlank
The string cannot be null, and the string after trim() cannot be equal to ""
@NotEmpty
cannot be null, and size() of collections, arrays, maps, etc. cannot be 0; string trim() can be equal to ""
POST http://localhost:8080/valid/test2
Content-Type: application/x-www-form-urlencoded
id=1&name=javadaily&level=12&email=476938977@qq.com&appId=ab1cdddd&sex=N
@Slf4j
public class UserValidation<T extends Annotation> implements ConstraintValidator<T, User> {
protected Predicate<User> predicate = c -> true;
@Resource
protected UserRepository userRepository;
@Override
public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) {
return userRepository == null || predicate.test(user);
}
/**
* 校验用户是否唯一
* 即判断数据库是否存在当前新用户的信息,如用户名,手机,邮箱
*/
public static class UniqueUserValidator extends UserValidation<UniqueUser>{
@Override
public void initialize(UniqueUser uniqueUser) {
predicate = c -> !userRepository.existsByUserNameOrEmailOrTelphone(c.getUserName(),c.getEmail(),c.getTelphone());
}
}
/**
* 校验是否与其他用户冲突
* 将用户名、邮件、电话改成与现有完全不重复的,或者只与自己重复的,就不算冲突
*/
public static class NotConflictUserValidator extends UserValidation<NotConflictUser>{
@Override
public void initialize(NotConflictUser notConflictUser) {
predicate = c -> {
log.info("user detail is {}",c);
Collection<User> collection = userRepository.findByUserNameOrEmailOrTelphone(c.getUserName(), c.getEmail(), c.getTelphone());
// 将用户名、邮件、电话改成与现有完全不重复的,或者只与自己重复的,就不算冲突
return collection.isEmpty() || (collection.size() == 1 && collection.iterator().next().getId().equals(c.getId()));
};
}
}
}
Copy after login
这里使用Predicate函数式接口对业务规则进行判断。
4.3. 测试代码
@RestController
@RequestMapping("/senior/user")
@Slf4j
@Validated
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping
public User createUser(@UniqueUser @Valid User user){
User savedUser = userRepository.save(user);
log.info("save user id is {}",savedUser.getId());
return savedUser;
}
@SneakyThrows
@PutMapping
public User updateUser(@NotConflictUser @Valid @RequestBody User user){
User editUser = userRepository.save(user);
log.info("update user is {}",editUser);
return editUser;
}
}
Copy after login
使用很简单,只需要在方法上加入自定义注解即可,业务逻辑中不需要添加任何业务规则的代码。
POST http://localhost:8080/valid/add
Content-Type: application/json
/senior/user
{
"userName" : "100001"
}
The above is the detailed content of How to use the SpringBoot parameter verification Validator framework. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn