Get请求使用注解校验失败

前言

今天在get请求上使用注解进行参数校验,怎么样都校验不到,把解决过程记录一下。

正文

解决方法 :

  1. 在类上面增加 @Validated 注解
  2. 修改方法访问权限为 public (我就栽在这里了,之前的接口在接手的时候使用的private修饰的)

这时就可以正常使用@NotNull 等各种校验注解了。

其它

需要注意的是这里校验失败时对外抛错是ConstraintViolationException(post请求对实体进行校验的抛错是MethodArgumentNotValidException)。
所以需要我们对两个抛错都进行处理。

   /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public CustomizeResponse exception(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);

        CustomizeResponse result = new CustomizeResponse();
        //result.setCode("");
        if(null != e.getBindingResult() && null != e.getBindingResult().getAllErrors() && !(e.getBindingResult().getAllErrors().isEmpty())){
            String errorMsg = e.getBindingResult().getAllErrors()
                    .stream()
                    .map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage())
                    .collect(Collectors.joining(","));
            if(null != errorMsg && !"".equals(errorMsg)){
                result.setMessage(errorMsg);
            }
        }

        return result;
    }

    /**
     * 处理参数校验异常(这个是处理方法校验的,用于get请求校验)
     * @param e
     * @return
     */
    @ExceptionHandler({ConstraintViolationException.class})
    public CustomizeResponse validateException(ConstraintViolationException e) {
        logger.error(e.getMessage(), e);

        CustomizeResponse result = new CustomizeResponse();
        //result.setCode("");
        if(null != e.getConstraintViolations() && !e.getConstraintViolations().isEmpty()){
            String errorMsg = e.getConstraintViolations()
                    .stream()
                    .map(objectError -> objectError.getMessage())
                    .collect(Collectors.joining(","));
            if(null != errorMsg && !"".equals(errorMsg)){
                result.setMessage(errorMsg);
            }
        }

        return result;
    }
原文地址:https://www.cnblogs.com/wmg92/p/13731238.html