springboot validation 参数嵌套
springboot validation 参数嵌套
如果需要对嵌套pojo检验,需要在嵌套参数前加@Valid,使嵌套pojo上的验证注解生效
*************************
示例
*********************
pojo 层
Product
@Data
public class Product {
@NotNull
private Integer prodId;
@NotNull
private String prodName;
@DecimalMin(value = "0.01",message = "价格不能小于0.01")
private BigDecimal price;
@Min(value = 1,message = "数量不能小于1")
private Integer amount;
}
Order
@Data
public class Order {
@NotNull
private String orderId;
@FutureOrPresent
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime orderTime;
@Valid
@NotNull
private List<Product> productList;
}
productList上加@Valid,使product的验证注解生效
*********************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(@Validated @RequestBody Order order, BindingResult result){
System.out.println(order);
if (result.hasFieldErrors()){
result.getFieldErrors().forEach(error -> {
System.out.print("field:"+error.getField());
System.out.println(" ==> message:"+error.getDefaultMessage());
});
}
return "success";
}
}
*************************
使用测试
localhost:8080/hello,设置header:Content-Type application/json,设置body:
![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzkzMTYyNQ_size_16_color_FFFFFF_t_70][]
productList 不加@Valid,控制台输出
2020-07-14 11:16:44.949 INFO 8972 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-14 11:16:44.956 INFO 8972 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 7 ms
Order(orderId=2, orderTime=2020-09-09T09:08, productList=[Product(prodId=1, prodName=苹果, price=10, amount=1), Product(prodId=2, prodName=香蕉, price=2, amount=0)])
没有对product进行检验,参数注解失效
prductList 加注解,控制台输出
2020-07-14 11:18:26.195 INFO 17364 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-14 11:18:26.199 INFO 17364 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Order(orderId=2, orderTime=2020-09-09T09:08, productList=[Product(prodId=1, prodName=苹果, price=10, amount=1), Product(prodId=2, prodName=香蕉, price=2, amount=0)])
field:productList[1].amount ==> message:数量不能小于1
productList[1].amount 报出错误,注解生效
还没有评论,来说两句吧...