后台数据校验
程序员文章站
2022-05-18 19:15:15
...
1.在方法参数中对实体进行声明@Valid和BindingResult result
2.通过解析BindingResult 并封装到map中,然后返回输出
3.实体的数据校验
@NotBlank(message = "用户昵称不能为空")
@Length(max = 12, message = "用户昵称不能超过12位")
@ApiModelProperty(value="用户昵称", name="nickname", example="杰森", required = false)
private String nickname;
@Length(max = 12, message = "用户真实姓名不能超过12位")
@ApiModelProperty(value="真实姓名", name="realname", example="杰森", required = false)
private String realname;
@Pattern(regexp = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$", message = "手机号格式不正确")
@ApiModelProperty(value="手机号", name="mobile", example="13999999999", required = false)
private String mobile;
@Email
@ApiModelProperty(value="邮箱地址", name="email", example="[email protected]", required = false)
private String email;
@Min(value = 0, message = "性别选择不正确")
@Max(value = 2, message = "性别选择不正确")
@ApiModelProperty(value="性别", name="sex", example="0:女 1:男 2:保密", required = false)
private Integer sex;
@ApiModelProperty(value="生日", name="birthday", example="1900-01-01", required = false)
private Date birthday;
public IMOOCJSONResult update(
@ApiParam(name = "userId", value = "用户id", required = true)
@RequestParam String userId,
@RequestBody @Valid CenterUserBO centerUserBO,
BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(centerUserBO);
// 判断BindingResult是否保存错误的验证信息,如果有,则直接return
if (result.hasErrors()) {
Map<String, String> errorMap = getErrors(result);
return IMOOCJSONResult.errorMap(errorMap);
}
}
private Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<>();
List<FieldError> errorList = result.getFieldErrors();
for (FieldError error : errorList) {
// 发生验证错误所对应的某一个属性
String errorField = error.getField();
// 验证错误的信息
String errorMsg = error.getDefaultMessage();
map.put(errorField, errorMsg);
}
return map;
}