The use of spring boot validated

Reprinted from: https://segmentfault.com/a/1190000011712893

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

a 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 it will be handled by the exception center.
BindingResult can also be used, but after using this, the exception must be handled manually, which invades the normal logic process and is not recommended.

Two common annotation types

Be careful not to misuse exception types, such as @size not available on int

Common 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 check

If a class contains another entity class, then add @Validated to it, such as the above

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

Four @pathvariable verification

spring-boot may not currently support validation of parameters: 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 solved in the next version of spring, or in service instead of @Pathvariable

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325747154&siteId=291194637