当前位置:网站首页>@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
边栏推荐
- The difference between restful and soap
- Learning note 5 - gradient explosion and gradient disappearance (k-fold cross verification)
- 使用 PHP PDO ODBC 示例的 Microsoft Access 数据库
- MySQL对数据表已有表进行分区表的实现
- Introduction to data analysis 𞓜 kaggle Titanic mission (IV) - > data cleaning and feature processing
- Pycharm
- Mba-day5 Mathematics - application problems - engineering problems
- 全栈交叉编译X86完成过程经验分享
- Embedded related surface (I)
- Simple thoughts on the design of a microblog database
猜你喜欢
Detailed explanation of typora Grammar (I)
Excel·VBA自定义函数获取单元格多数值
After the MySQL router is reinstalled, it reconnects to the cluster for boot - a problem that has been configured in this host before
精彩回顾|「源」来如此 第六期 - 开源经济与产业投资
Visual solutions to common problems (VIII) mathematical formulas
26. 删除有序数组中的重复项
About the three commonly used auxiliary classes of JUC
Ueditor -- limitation of 4m size of image upload component
An interesting interview question
Introduction to data analysis 𞓜 kaggle Titanic mission (III) - > explore data analysis
随机推荐
The courses bought at a high price are open! PHPer data sharing
闹钟场景识别
Use of SVN:
高价买来的课程,公开了!phper资料分享
Pytorch implementation of transformer
Mba-day5 Mathematics - application problems - engineering problems
Reading integrity monitoring techniques for vision navigation systems - 5 Results
MBA - day5 mathématiques - Questions d'application - Questions d'ingénierie
Latex usage
ID number verification system based on visual structure - Raspberry implementation
Mysql8.0安装指南
Visual common drawing (V) scatter diagram
Notes on concurrent programming of vegetables (V) thread safety and lock solution
How to bind a process to a specified CPU
Excel · VBA custom function to obtain multiple cell values
Mba-day6 logic - hypothetical reasoning exercises
About the three commonly used auxiliary classes of JUC
Excel·VBA数组冒泡排序函数
The difference between restful and soap
Intuitive understanding entropy