这篇文章将简单的整合下JSR 303,后面还会不断的添加新的内容
SpringBoot整合JSR 303步骤:
- 引入依赖
<!--整合JSR 303参数校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- 对bean对象加注解
@Data
@TableName(value = "user")
public class User {
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@NotBlank(message = "姓名不能为null")
private String name;
@NotNull
@Min(value = 0, message = "age必须大于0")
private Integer age;
}
- 在Controller层加上注解
@PostMapping("/insert")
public String insert(@RequestBody @Valid User user, BindingResult bindingResult){
String s="";
if (bindingResult.hasErrors()){
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError error : allErrors) {
String name = error.getObjectName();
String message = error.getDefaultMessage();
s+=name+message;
}
}else {
userService.inserUser(user);
s = "插入成功";
}
return s;
}