软件编程
位置:首页>> 软件编程>> java编程>> 使用注解@Validated效验VO参数是否合规

使用注解@Validated效验VO参数是否合规

作者:Kason  发布时间:2023-10-27 20:13:01 

标签:@Validated,VO,注解,参数校验

一:引入依赖包

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-validation</artifactId>
       </dependency>

二:在注解里标记清楚规则

@Data
public class Test01VO {

@NotNull(message = "ID不能为空")
   private Integer id;
   @Min(0)
   @Max(5)
   private Integer score;
   private String content;
}

三:在Controller里使用@Validated注解

@PostMapping("/test01")
   public String test(@Validated @RequestBody Test01VO test01vo) {
       System.out.print("test>>>>>>>>>"+test01vo.getId());
       return "success";
   }

四:调用接口验证是否生效

参数:

{
   "id": "",
   "score": 5
}

返回参数异常:

{
   "code": 410,
   "msg": "ID不能为空; ",
   "data": null,
   "traceId": null
}

参数:

{
   "id": "1",
   "score": "10"
}

返回参数异常:

{
   "code": 410,
   "msg": "must be less than or equal to 5; ",
   "data": null,
   "traceId": null
}

参数:

{
   "id": "1",
   "score": 5
}

返回值:

success

来源:https://segmentfault.com/a/1190000043781388

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com