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!
Statement of this 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
Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.
1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points
Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick
Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input
SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable
1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe
When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to
In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic