文章目录
1. 不优雅的参数校验
后端对前端传过来的参数是需要进行校验的,如果在controller中直接校验需要用大量的if else做判断。以添加用户的接口为例,需要对前端传过来的参数进行校验, 如下的校验就是不优雅的:
@PostMapping("add")
public ResponseEntity<String> add(User user) {
if(user.getName()==null) {
return ResponseResult.fail("user name should not be empty");
} else if(user.getName().length()<5 || user.getName().length()>50){
return ResponseResult.fail("user name length should between 5-50");
}
if(user.getAge()< 1 || user.getAge()> 150) {
return ResponseResult.fail("invalid age");
}
// ...
return ResponseEntity.ok("success");
}
2. Validation 中的常见constraint
@DecimalMax(value):被注解的元素必须为一个数字,其值必须小于等于指定的最小值
@DecimalMin(Value):被注解的元素必须为一个数字,其值必须大于等于指定的最小值
@Digits(integer=, fraction=):被注解的元素必须为一个数字,其值必须在可接受的范围内
@Email:被注释的元素必须是电子邮箱
@Future:被注解的元素必须是日期,必须是将来日期
@Past:被注解的元素必须是日期,必须是过去日期
@Max(value):被注解的元素必须为一个数字,其值必须小于等于指定的最大值
@Min(value):被注解的元素必须为一个数字,其值必须大于等于指定的最小值
@NotNull:被注解的元素必须不为null
@NotBlank:CharSequence子类型,验证注解的元素值不为空(包括不为null或去除首尾空格后长度为0)
@NotEmpty:被注释的对象必须不为空(数据:String,Collection,Map,arrays)
@Size(min=, max=):被注解的元素必须在制定的范围(对象、数组或集合的大小)
@Pattern(regex=, flag=):被注解的元素必须符合正则表达式
3. 举例:请求参数封装并添加validation注解约束和message
将查询用户的参数封装到UserParam中, 而不是User(数据库实体)本身。
public class UserParam implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message = "could not be empty")
private String userId;
@NotEmpty(message = "could not be empty")
@Email(message = "invalid email")
private String email;
@NotEmpty(message = "could not be empty")
@Pattern(regexp = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$", message = "invalid ID")
private String cardNo;
@NotEmpty(message = "could not be empty")
@Length(min = 1, max = 10, message = "nick name should be 1-10")
private String nickName;
@NotEmpty(message = "could not be empty")
@Range(min = 0, max = 1, message = "sex should be 0-1")
private int sex;
@Max(value = 100, message = "Please input valid age")
private int age;
@Valid
private AddressParam address;
}
4. controller层使用参数校验
使用@Valid或者@Validated注解。
@PostMapping("add")
public ResponseEntity<String> add(@Valid @RequestBody UserParam userParam)