3.2 JSR 参数校验与拦截

1 引入JSR依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
  </dependencies>

2 校验

  • 1 添加 @Valid 标签
public Result<Boolean> doLogin(LoginVo loginVo){
--> 
public Result<Boolean> doLogin(@Valid LoginVo loginVo){
  • 2 在校验的实体类中添加@NotNull 标签
@NotNull@IsMobile
private String mobile;@NotNull@Length(min=32)
private String password;
  • 3 编写接口 并制定校验器
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
    boolean require() default true;    String message() default "手机号码格式错误";    Class<?>[] groups() default {};    Class<? extends Payload>[] payload() default {};}
  • 4 重新编写校验器
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
    private boolean required = false;    @Override    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.require();    }

    @Override    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(required){
            return ValidatorUtil.isMobile(value);        }else{
            if(StringUtils.isEmpty(value)){
                return true;            }else{
                return ValidatorUtil.isMobile(value);            }
        }
    }
}

3 拦截

  • 创建exception 包和GlobelExceptionHandler 类
@ControllerAdvice@ResponseBodypublic class GlobleExceptionHandler {
    @ExceptionHandler(value=Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e){

        if(e instanceof BindException){
            BindException ex = (BindException) e;            List<ObjectError> errors = ex.getAllErrors();            ObjectError error  = errors.get(0);            String msg = error.getDefaultMessage();            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));        }else{
            return Result.error(CodeMsg.SERVER_ERROR);        }
    }
}

4 编写全局异常

public class GlobleException extends RuntimeException{

    private static final long serialVersionUID = 7103829434715939102L;    public CodeMsg getCm() {
        return cm;    }

    private CodeMsg cm;    public GlobleException(CodeMsg cm){
        super(cm.toString());        this.cm = cm;    }
}

5 在sevice层遇到异常,直接抛出异常

    public CodeMsg login(LoginVo loginVo) {
        if(loginVo == null){
//            return CodeMsg.SERVER_ERROR;            throw new GlobleException(CodeMsg.SERVER_ERROR);        }
posted @ 2021-07-10 21:38  weidalin  阅读(85)  评论(0)    收藏  举报