当前位置:网站首页>@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
边栏推荐
- Excel · VBA array bubble sorting function
- Promise详解
- Mysql8. 0 installation guide
- 学习 Go 语言 0x06:《Go 语言之旅》中 斐波纳契闭包 练习题代码
- remote: Support for password authentication was removed on August 13, 2021.
- Visualization Road (11) detailed explanation of Matplotlib color
- mysql中整数数据类型tinyint详解
- 如何使用JDBC CallableStatement.wasNull()方法调用来查看最后一个OUT参数的值是否为 SQL NULL
- Mysql中有关Datetime和Timestamp的使用总结
- 全栈交叉编译X86完成过程经验分享
猜你喜欢

Introduction to data analysis 𞓜 kaggle Titanic mission (III) - > explore data analysis

Excel·VBA数组冒泡排序函数

Source insight 4.0 FAQs

Microsoft Access database using PHP PDO ODBC sample

26. 删除有序数组中的重复项

MIT:用无监督为世界上每个像素都打上标签!人类:再也不用为1小时视频花800个小时了

Visualization Road (11) detailed explanation of Matplotlib color

Learning note 5 - gradient explosion and gradient disappearance (k-fold cross verification)

使用 PHP PDO ODBC 示例的 Microsoft Access 数据库

The songbird document editor will be open source: starting with but not limited to markdown
随机推荐
Notes on concurrent programming of vegetables (V) thread safety and lock solution
An interesting interview question
MySQL分区表实现按月份归类
精彩回顾|「源」来如此 第六期 - 开源经济与产业投资
Precautions for latex formula
Excel · VBA custom function to obtain multiple cell values
STM32接电机驱动,杜邦线供电,然后反烧问题
How to quickly download vscode
Learning website materials
C语言之结构体(进阶篇)
Mysql中有关Datetime和Timestamp的使用总结
Resolution and size of mainstream mobile phones
Google Earth Engine(GEE)——将原始影像进行升尺度计算(以海南市为例)
Difference between pregnancy box and delivery box
MySQL8.0升级的踩坑历险记
Introduction to neo4j authoritative guide, recommended by Qiu Bojun, Zhou Hongxiang, Hu Xiaofeng, Zhou Tao and other celebrities
Excel·VBA数组冒泡排序函数
Esp32 learning - add folder to project
Latex usage
学习 Go 语言 0x07:《Go 语言之旅》中 Stringer 练习题代码