Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Writing in the front
When we are developing on the Web side, we always need to do some validation of some incoming parameters, such as whether they are empty, whether they conform to the format and so on.
In order to make development easier and more efficient, there are several parameter validation components on the market. Today we are going to study the Validation component.
We’ll cover some of this next, as well as the associated integration process into the SpringBoot project. Take a look.
The integration process
First, let’s introduce the relevant JAR packages.
< the dependency > < groupId > javax.mail. Validation < / groupId > < artifactId > validation - API < / artifactId > < version > 2.0.1. The Final < / version > </dependency>Copy the code
As you can see in the code above, this is the core component package for Validation, and we don’t have to do this here.
If you have already introduced the following Spring-boot-starter-Web related JAR packages.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code
All that’s left is to use it in the actual entity class.
How to use
We need to have a Controller class to write the interface.
@RestController
@RequestMapping("/test")
public class ConfigController {
@GetMapping("/save")
public String save(@RequestBody TestPO po){
return ""; }}Copy the code
In the code above, we now have a Controller, and then we use the Validation component in the Controller. We just need to start the validation parameter with a @valid annotation in front of the TestPO Po.
Then we configure the validation rules for specific parameters in the TestPO class.
public class TestPO {
/** * User name */
@notblank (message = "User name cannot be blank!" )
private String username;
}
Copy the code
As you can see in the code above, you just need to add @notblank to validate the rule for username.
summary
Of course, there are many other annotations that we can develop besides NotBlank annotations, and we will continue to include other annotations in the next article.