1.需求分析
2.思路分析
3.引入依赖 JSR303
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
4.在Furn的属性上添加注解校验
@NotEmpty(message = "请输入家居名")
private String name;
@NotEmpty(message = "请输入制造厂商")
private String maker;
@NotNull(message = "请输入数字")
@Range(min = 0, message = "价格不能小于0")
private BigDecimal price;
@NotNull(message = "请输入数字")
@Range(min = 0, message = "销量不能小于0")
private Integer sales;
@NotNull(message = "请输入数字")
@Range(min = 0, message = "库存不能小于0")
private Integer stock;
5.在Controller中进行校验 FurnController.java
@ResponseBody
@PostMapping("/save")
public Msg save(@Validated @RequestBody Furn furn, Errors errors) {
Map<String, Object> errorMap = new HashMap<>();
List<FieldError> fieldErrors = errors.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
}
if (errorMap.isEmpty()) {
furnService.save(furn);
return Msg.success();
} else {
return Msg.fail().add("errMsg", errorMap);
}
}
6.postman测试
7.后端校验,整合前端
1.数据池中添加信息,存储错误信息
2.将后端返回的信息放到数据池中
3.单向绑定,取出数据展示
4.放行前端校验进行测试
5.结果展示