The use of @validated in Spring annotations

In spring-boot, @validated can be used to verify the data. If the data is abnormal, an exception will be thrown uniformly to facilitate the unified processing of the exception center.
For example, to determine whether an input parameter is legal, we can use the following method

1. Basic use
Because spring-boot has introduced the basic package, it can be used directly.
1 First declare on the controller that the data needs to be verified

@RequestMapping(value="/url.json",method= {RequestMethod.POST})
@ResponseBody
@Transactional
public Result<?> xxmethod( @RequestBody @Validated  XoPO xoPo)     
    throws ParseException, UnsupportedEncodingException {}

2 Then declare the fields that need to be verified on the bean

@data
public class XoPO{
    
    @validated
    private List<OrderPerson> personList;
    
    @NotNull
    @Size(max=32,message="code is null")
    private String code;

    @NotBlank
    @Size(max=32,message="product is null")
    private String product;
}

Then, when the input fails to meet the conditions, an exception will be thrown, and then processed by the exception center.
BindingResult can also be used, but after using this, you must manually handle the exception, invading the normal logic process, and it is not recommended

Two commonly used annotation types
Note, do not use the exception type by mistake, for example, @size is not available on int

Commonly used annotations are as follows

@AssertFalse 校验false
@AssertTrue 校验true
@DecimalMax(value=,inclusive=) 小于等于value,
inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 与上类似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull  检查Null
@Past  检查日期
@Pattern(regex=,flag=)  正则
@Size(min=, max=)  字符串,集合,map限制大小
@Validate 对po实体类进行校验

Three-nested validation
If a class contains another entity class, just add @Validated on it, such as the above

public class XoPO {    
    @validated
    private List<PersonDetailPO> personList;
 }

Four @pathvariable verification
spring-boot may not currently support parameter verification: https://jira.spring.io/browse…

public Result<?> xoById( @NotNull @NotBlank @Size(min=10,max=32)@PathVariable(value="accountId") String id) {}

But it is not yet possible to throw an exception, which may be resolved in the next version of spring, or in the service without @Pathvariable

Class XoService{
   public xoMethon( @NotNull String id){
   }
}

Guess you like

Origin blog.csdn.net/m0_43413873/article/details/123200517