当前位置:网站首页>@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
边栏推荐
- 学习 Go 语言 0x04:《Go 语言之旅》中切片的练习题代码
- FileProvider 路径配置策略的理解
- colab
- Esp32 learning - use and configuration of GPIO
- Which company is good for opening futures accounts? Who can recommend several safe and reliable futures companies?
- Using El popconfirm and El backtop does not take effect
- 学习 Go 语言 0x02:对切片 Slice 的理解
- 闹钟场景识别
- Facing the global market, platefarm today logs in to four major global platforms such as Huobi
- Database management software sqlpro for SQLite for Mac 2022.30
猜你喜欢

VIM + ctags + cscope development environment construction guide

Introduction to data analysis 𞓜 kaggle Titanic mission (IV) - > data cleaning and feature processing

Excel · VBA array bubble sorting function

About the three commonly used auxiliary classes of JUC

一道有趣的阿里面试题

Intuitive understanding entropy

Visual common drawing (III) area map

《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐

Visual common drawing (I) stacking diagram

Solutions to common problems in visualization (VIII) solutions to problems in shared drawing area
随机推荐
Mysql排序的特性详情
Visualization Road (11) detailed explanation of Matplotlib color
语雀文档编辑器将开源:始于但不止于Markdown
Visual Road (XII) detailed explanation of collection class
How to bind a process to a specified CPU
Embedded related surface (I)
Learning notes 7-depth neural network optimization
Google Earth Engine(GEE)——将原始影像进行升尺度计算(以海南市为例)
活动进行时! 点击链接加入直播间参与“AI真的能节能吗?”的讨论吧!
使用zerotier让异地设备组局域网
Introduction to data analysis 𞓜 kaggle Titanic mission (IV) - > data cleaning and feature processing
Idea - indexing or scanning files to index every time you start
Using El popconfirm and El backtop does not take effect
学习 Go 语言 0x08:《Go 语言之旅》中 练习使用 error
闹钟场景识别
Precautions for latex formula
Reading integrity monitoring techniques for vision navigation systems - 5 Results
Learning note 5 - gradient explosion and gradient disappearance (k-fold cross verification)
Excel·VBA数组冒泡排序函数
Analysis on the characteristics of the official game economic model launched by platoffarm