当前位置:网站首页>@Valid, @ validated learning notes
@Valid, @ validated learning notes
2022-04-23 11:04:00 【Mu_ Mu is a little white】
1. brief introduction
- @Validated: Can be used in type 、 Method and method parameters . But it can't be used in member properties ( Field ) On , Nested detection is not supported
- @Valid: It can be used in methods 、 Constructors 、 Method parameters and member properties ( Field ) On , Support nested detection
2. introduce maven
springboot 2.3.0 It will not be imported automatically in the future jar package , So add the following maven,2.3 In the past, there was no need to introduce maven package
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
3. Use notes together
@Null The limit can only be null
@NotNull The limit must not be null
@AssertFalse The limit must be false
@AssertTrue The limit must be true
@DecimalMax(value) The limit must be a number no greater than the specified value
@DecimalMin(value) The limit must be a number not less than the specified value
@Digits(integer,fraction) The limit must be a decimal , And the number of digits in the integer part cannot exceed integer, The number of decimal places cannot exceed fraction
@Future The limit must be a future date
@Max(value) The limit must be a number no greater than the specified value
@Min(value) The limit must be a number not less than the specified value
@Past The limit must be a date in the past
@Pattern(value) The restriction must conform to the specified regular expression
@Size(max,min) The limit character length must be in min To max Between
@Past Verify the element value of the annotation ( The date type ) Earlier than the current time
@NotEmpty Verify that the element value of the annotation is not null It's not empty ( String length is not 0、 The set size is not 0)
@NotBlank Verify that the element value of the annotation is not empty ( Not for null、 The length after removing the first space is 0), differ @NotEmpty,@NotBlank It only applies to strings and will remove the space of strings when comparing
@Email Verify that the element value of the annotation is Email, You can also use regular expressions and flag Specify custom email Format
4. Example
4.1 model
@Valid Definition schoole Property is for nested validation , Without this annotation, you can't verify school Properties that need to be verified inside the class .
public class UserVO {
@NotNull(message = "id Can't be empty ." ,groups = {Insert.class})
private Integer id;
@NotBlank(message = "name Can't be empty .",groups = {Update.class})
private String name;
@NotNull(message = "schoole Can't be empty .")
@Valid
private Schoole schoole;
@Min(value = 1,message = "age Not less than 1")
@Max(value = 130,message = "age Not greater than 130")
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Schoole getSchoole() {
return schoole;
}
public void setSchoole(Schoole schoole) {
this.schoole = schoole;
}
public class Schoole {
@NotBlank(message = "name Can't be empty .",groups = {Update.class})
private String name;
@NotNull(message = "id Can't be empty ")
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
4.3 Packet interface
Realization Default Interface otherwise @Validated({Update.class}) Use Update In groups , The default verification property of undefined groups will not take effect ( Like verification schoole Of @NotNull(message = “schoole Can't be empty .”))
import javax.validation.groups.Default;
public interface Insert extends Default {
}
public interface Update extends Default {
}
4.4controller
@Validated mark group when (Update.class) Only the verification annotation on the verification attribute needs to contain the interface (Update.class) To take effect , If group (Update.class) Realized Default If the interface needs to be verified, the verification annotation on the verification attribute does not define any group It will also take effect when .
@RestController
@RequestMapping("/valid")
public class TestValidController {
private static final Logger LOG = LoggerFactory.getLogger(TestValidController.class);
@RequestMapping("/test")
public void testValid(@Validated({Update.class}) UserVO userVO){
LOG.info("userVo:"+userVO);
}
@PostMapping("/test2")
public void testValid2(@Validated() @RequestBody UserVO userVO){
LOG.info("userVo:"+userVO);
}
}
4.5 Use the global exception interceptor to intercept parameter verification exceptions
MethodArgumentNotValidException Anomaly caused by @RequestBody The decorated parameter has not been verified. Throw , Other exceptions that fail to pass the verification are thrown BindException.
@RestControllerAdvice
public class GlobalExceptionHandler {
private Logger LOG= LoggerFactory.getLogger(GlobalExceptionHandler.class);
//BindException Thrown if the verification parameters do not meet the conditions
@ExceptionHandler(BindException.class)
public Object handleValidException(BindException e) {
return ResponseUtil.fail(400,e.getBindingResult().getFieldError().getDefaultMessage());
}
//MethodArgumentNotValidException @RequestBody The decorated parameter has not been verified. Throw
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleValidException2(MethodArgumentNotValidException e) {
return ResponseUtil.fail(400,e.getBindingResult().getFieldError().getDefaultMessage());
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseUtil handleRuntimeException(RuntimeException ex) {
int code = 500;
String message = ex.getMessage();
ex.printStackTrace();
LOG.error(ex.getMessage());
return ResponseUtil.fail(code,message);
}
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseUtil handleException(Exception ex) {
int code = 500;
String message = ex.getMessage();
ex.printStackTrace();
LOG.error(ex.getMessage());
return ResponseUtil.fail(code,message);
}
}
版权声明
本文为[Mu_ Mu is a little white]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231053252066.html
边栏推荐
- How to quickly download vscode
- SVN的使用:
- Database management software sqlpro for SQLite for Mac 2022.30
- vm设置静态虚拟机
- Microsoft Access database using PHP PDO ODBC sample
- 防止web项目中的SQL注入
- MySQL Router重装后重新连接集群进行引导出现的——此主机中之前已配置过的问题
- Analysis on the characteristics of the official game economic model launched by platoffarm
- mysql创建存储过程及函数详解
- Derivation and regularization
猜你喜欢
Go interface usage
CUMCM 2021-B:乙醇偶合制備C4烯烴(2)
Solution architect's small bag - 5 types of architecture diagrams
UEditor之——图片上传组件大小4M的限制
ID number verification system based on visual structure - Raspberry implementation
Notes on concurrent programming of vegetables (V) thread safety and lock solution
《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐
The courses bought at a high price are open! PHPer data sharing
Ueditor -- limitation of 4m size of image upload component
精彩回顾|「源」来如此 第六期 - 开源经济与产业投资
随机推荐
如何使用JDBC CallableStatement.wasNull()方法调用来查看最后一个OUT参数的值是否为 SQL NULL
Notes on concurrent programming of vegetables (IX) asynchronous IO to realize concurrent crawler acceleration
CUMCM 2021-B:乙醇偶合制备C4烯烃(2)
SWAT—Samba WEB管理工具介绍
Read integrity monitoring techniques for vision navigation systems - 4 multiple faults in vision system
Constraintlayout layout
Esp32 learning - use and configuration of GPIO
Google Earth Engine(GEE)——将原始影像进行升尺度计算(以海南市为例)
Understand the key points of complement
Mysql排序的特性详情
A diary of dishes | 238 Product of arrays other than itself
Use of SVN:
CUMCM 2021-B:乙醇偶合制備C4烯烴(2)
Cumcm 2021 - B: préparation d'oléfines C4 par couplage éthanol (2)
一道有趣的阿里面试题
Xdotool key Wizard
Alarm scene recognition
HuggingFace
Mysql8. 0 installation guide
Visual common drawing (III) area map