参数验证的目的
作为一个好的服务端的开发人员,对于外部传入的参数一定要做参数验证,我们使用springboot可以方便的利用内置的javax.validation
包来进行参数的验证
RequestParam类型参数的验证
对于RequestParam类型参数的验证,需要在controller类上面加入@Validated
注解
例子1
下面的例子就是简单的post方法中的form表单参数验证
@Validated
public class SampleWebParamValidController {
@PostMapping("/param")
public BaseResult param(
@Max(value = 100, message = "int1不能大于100")
@Min(value = 18, message = "int1不能小于18")
@RequestParam Integer int1,
@NotNull(message = "int2必须存在")
@RequestParam Integer int2,
@PositiveOrZero(message = "int3必须是正数或0")
@RequestParam Integer int3,
@RequestParam(required = false, defaultValue = "100") Integer int4,
@NotEmpty(message = "str1不能为空")
@RequestParam String str1,
@Length(min = 2, max = 10, message = "str2长度在2~10字符")
@RequestParam String str2,
@AssertTrue(message = "bool1必须为正")
@RequestParam Boolean bool1) {
UserDomain userDomain = new UserDomain();
userDomain.setBool1(bool1);
userDomain.setInt1(int1);
userDomain.setInt2(int2);
userDomain.setInt4(int4);
userDomain.setInt3(int3);
userDomain.setStr1(str1);
userDomain.setStr2(str2);
return BaseResult.success(userDomain);
}
}
例子2
下面的例子就是简单的post方法中的form表单中有复杂参数验证
@Validated
public class SampleWebParamValidController {
@PostMapping("/listParam")
public BaseResult listParam(
@Size(min = 1, max = 4, message = "list1长度元素必须是1-4个")
@RequestParam List<String> list1) {
UserDomain userDomain = new UserDomain();
userDomain.setList1(list1);
return BaseResult.success(userDomain);
}
}
RequestBody类型参数的验证
对于RequestBody类型参数的验证,需要在@RequestBody
参数前面加上@Valid
注解
例子3
下面的例子就是简单的post方法中的单个requestbody中有参数验证
@PostMapping("/listBody")
public BaseResult listBody(
@Valid
@Size(min = 1, max = 4, message = "list1长度元素必须是1-4个")
@RequestBody List<String> list1) {
UserDomain userDomain = new UserDomain();
userDomain.setList1(list1);
return BaseResult.success(userDomain);
}
例子4
下面的例子就是简单的post方法中的requestbody中有对象参数验证
@PostMapping("/validReqeustBody")
public BaseResult addUserErrorAge(@Valid @RequestBody UserDomain userDomain) {
log.info("userDomain:{}", userDomain);
return BaseResult.success(userDomain);
}
@Data
public class UserDomain {
@Max(value = 100, message = "int1不能大于100")
@Min(value = 18, message = "int1不能小于18")
private Integer int1;
@NotNull(message = "int2必须存在")
private Integer int2;
@PositiveOrZero(message = "int3必须是正数或0")
private Integer int3;
private Integer int4 = 10;
@NotEmpty(message = "str1不能为空")
private String str1;
@Length(min = 2, max = 10, message = "str2长度在2~10字符")
private String str2;
@Size(min = 1, max = 4, message = "list1长度元素必须是1-4个")
private List<String> list1;
@Size(min = 2, max = 6, message = "list2长度元素必须是2-6个")
private List<Integer> list2;
@AssertTrue(message = "bool1必须为正")
private Boolean bool1;
}
网友评论