1.写校验
@Api(value = "用户信息")
@Data
public class UserVO {
@ApiModelProperty(value = "用户ID")
private Integer id ;
@NotEmpty(message = "用户名不能为空")
@Length(min =6,max = 12,message = "长度在6-12之间")
@ApiModelProperty(value = "用户名")
private String username;
@NotEmpty(message = "密码不能为空")
@Length(min =6,message = "长度不能小于6")
@ApiModelProperty(value = "密码")
private String password;
@Email(message = "请输入正确的email")
private String email;
@Pattern(regexp = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$",message = "身份证格式错误")
private String idCard;
@ApiModelProperty(value = "性别 0=女 1=男")
private Byte sex;
@ApiModelProperty(value = "删除标志")
private Byte deleted;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
}
2.加一个体验类
@PostMapping(value = "/user/create")
public void createUser(@RequestBody @Validated UserVO userVO){
}
3.Validation常用注解
https://blog.csdn.net/qq_20262765/article/details/90070203
4.自定义一个Validation的注解
写一个手机号码的校验的Validation注解
public class PhoneValidator implements ConstraintValidator<Phone,String> {
private static final Pattern PHONE_PATTERN = Pattern.compile(
"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$"
);
@Override
public void initialize(Phone constraintAnnotation) {
}
//实现逻辑
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if(value == null || value.length() == 0){
return true;
}
Matcher m = PHONE_PATTERN.matcher(value);
return m.matches();
}
}
手机号码类
@Documented
@Constraint(validatedBy = PhoneValidator.class)
@Target({METHOD,FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "请输入正确的手机号码";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List{
Phone[] value();
}
}
给手机类加注解
@com.boot.swagger.annotation.Phone
private String Phone;
5.把报错加入异常处理
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ErrorResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e,HttpServletRequest request){
String msgs = this.handle(e.getBindingResult().getFieldErrors());
ErrorResult error = ErrorResult.fail(ResultCode.PARAM_IS_INVALID,e,msgs);
log.error("url:{},参数校验异常",request.getRequestURL(),error);
return error;
}
private String handle(List<FieldError> fielderror){
StringBuilder sb = new StringBuilder();
for(FieldError obj : fielderror){
sb.append(obj.getField());
sb.append("=[");
sb.append(obj.getDefaultMessage());
sb.append("] ");
}
return sb.toString();
}
问题
1.byte的性别自定义异常怎么处理
2.错误的异常能捕获,正确的为什么走了系统异常10000