https://zhuanlan.zhihu.com/p/58204406
简化验证为空,什么的.提高效率
老式验证代码繁琐
@RestController
@RequestMapping("/student")
public class ValidateOneController {
@GetMapping("/id")
public Student findStudentById(Integer id){
if(id == null){
logger.error("id 不能为空!");
throw new NullPointerException("id 不能为空");
}
return studentService.findStudentById(id);
}
}
标题实体类校验代码
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer id;
@NotBlank(message = "学生名字不能为空")
@Length(min = 2, max = 10, message = "name 长度必须在 {min} - {max} 之间")
private String name;
@NotNull(message = "年龄不允许为空")
@Min(value = 0, message = "年龄不能低于 {value} 岁")
private Integer age;
}
controller验证
@Validated //开启数据校验,添加在类上用于校验方法,添加在方法参数中用于校验参数对象。(添加在方法上无效)
@RestController
@RequestMapping("/student")
public class ValidateOneController {
/**
* 普通参数校验
* @param name
* @return
*/
@GetMapping("/name")
public String findStudentByName(@NotBlank(message = "学生名字不能为空")
@Length(min = 2, max = 10, message = "name 长度必须在 {min} - {max} 之间")String name){
return "success";
}
/**
* 对象校验
* @param student
* @return
*/
@PostMapping("/add")
public String addStudent(@Validated @RequestBody Student student){
return "success";
}
}