- 首先是validation
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- controller,vo标上相应的注解
//controller
public RespBean doLogin(@Valid LoginVo loginVo){}
//vo
@Data
public class LoginVo {
@NotNull
@IsMobile
private String mobile;
@NotNull
private String password;
}
- 写自定义注解
@Constraint(validatedBy = {具体验证类的.class} )
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { IsMobileValidator.class})
public @interface IsMobile {
boolean required() default true;
// message是违反验证时会报的信息
String message() default "手机号格式错误";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
-注解的具体验证类(根据此类判断是否验证通过)
//需要实现ConstraintValidator<annotation,T>,annotation是自定义的注解,T是你所标注注解地方上的字段比如Mobile的具体值,比如前段传过来的手机号为xxx,为字符串类型,然后这里的value就是手机号值。
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
private boolean required = false;
@Override
public void initialize(IsMobile constraintAnnotation) {
required = true;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (required){
return ValidatorUtil.isMobile(value);
}
return true;
}
}
- RestControllerAdvice
首先需要一个继承RuntimeException的自定义异常类,可以需要一个属性,抛出异常时可以new GlobalException(),传入参数
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{
private RespBeanEnum respBeanEnum;
}
然后需要一个handlcer,根据抛出的异常,返回对应异常的错误给前端
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public RespBean exceptionHandler(Exception e){
if (e instanceof GlobalException){
GlobalException ex = (GlobalException) e;
return RespBean.error(ex.getRespBeanEnum());
}else if (e instanceof BindException){
BindException ex = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
respBean.setMsg("参数校验异常"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return respBean;
}
return RespBean.error(RespBeanEnum.ERROR);
}
}