Spring boot field annotation form format control (regular verification), and front-end return code after interception--Rookie Xiaohui

Spring boot field annotation format control (regular verification), and front-end return code after interception

Annotation configuration

  • Annotate directly on the entity class field to intercept
@NotBlank(message = "请输入密码")
@Pattern(regexp = "\\w{6,18}$",message = "账号应为6-18位字符,不含特殊符号,添加失败")
private String userAccount;
@NotBlank(message = "请输入密码")
@Pattern(regexp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$",message = "账号应为6-18位字符,包含数字和字母,不含特殊符号,添加失败")
private String userPwd;

For more annotations, please refer to the blog post: Annotation Verification of Entity Class Fields

Configure the return message when interception is successful

(img-CtjD5TSP-1591177962428)(http://hbq.idse.top/blog/1591177636347.png)]

  • @Valid: means to join the interception
  • BindingResult result: used to format the return information
  • returnUnifiedError(result): The method is used to process the intercepted return information
    Related codes:
# controller:
@PostMapping("/addNkbUser")
public ResultObject addNkbUser(@Valid @RequestBody NkbUserDTO nkbUserDTO,BindingResult result){
	if(result.hasErrors()){
		returnUnifiedError(result);
		return new ResultObject(StatusCode.ERROR,returnUnifiedError(result));
	}
	return iNkbUserService.addNkbUser(nkbUserDTO);
}
# 错误处理方法
public String returnUnifiedError(BindingResult bindingResult) {
	StringBuilder errorMsg = new StringBuilder();
	bindingResult.getAllErrors().stream().forEach(
			error -> {
				FieldError fieldError = (FieldError) error;
				errorMsg.append(fieldError.getDefaultMessage() + ";");
			}
	);
	return errorMsg.toString();
}

Guess you like

Origin blog.csdn.net/qq_39231769/article/details/106529717