代码之家  ›  专栏  ›  技术社区  ›  SpringUser

@NotNull:验证自定义消息未显示

  •  0
  • SpringUser  · 技术社区  · 6 年前

    我正在使用SpringDataJPA创建应用程序。在这一点上,我尝试使用注释实现服务器端验证。我补充说 @NotNull 上的注释已与自定义消息一起存档。我还补充说 @valid 具有 @RequestBody

    但问题是我路过的时候 nAccountId 作为 null 我没有收到自定义消息,即 Account id can not be null 我收到“留言”: "Validation failed for object='accountMaintenanceSave'. Error count: 1", .

    有人能告诉我为什么我没有收到定制信息吗?

    控制器代码

    @PutMapping("/updateAccountData")
    public ResponseEntity<Object> saveData(@Valid @RequestBody AccountMaintenanceSave saveObj){
        return accService.saveData(saveObj);
    } 
    

    AccountMaintenanceSave类

    import javax.validation.constraints.NotNull;
    
    public class AccountMaintenanceSave {   
    
        @NotNull(message="Account id can not be null")
        public Integer nAccountId;
        @NotNull
        public String sClientAcctId;
        @NotNull
        public String sAcctDesc;
        @NotNull
        public String sLocation;
        @NotNull
        public Integer nDeptId; 
        @NotNull
        public Integer nAccountCPCMappingid;
        @NotNull
        public Integer nInvestigatorId;
    
        //Getter and Setter
    }
    

    RestExceptionHandler类

    @ControllerAdvice
    public class RestExceptionHandler { 
    
        @ExceptionHandler(Exception.class)
        public ResponseEntity<Object> handleAllExceptionMethod(Exception ex, WebRequest requset) {
    
            ExceptionMessage exceptionMessageObj = new ExceptionMessage();
    
            exceptionMessageObj.setMessage(ex.getLocalizedMessage());
            exceptionMessageObj.setError(ex.getClass().getCanonicalName());
            exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());
    
            // return exceptionMessageObj;
            return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    

    我不知道以前到底发生了什么,也没有得到正确的信息。现在使用相同的代码,通过正确的消息得到这样的结果

    {
      "message": "Validation failed for argument at index 0 in method: public org.springframework.http.ResponseEntity<java.lang.Object> com.spacestudy.controller.AccountController.saveData(com.spacestudy.model.AccountMaintenanceSave), with 1 error(s): [Field error in object 'accountMaintenanceSave' on field 'nAccountId': rejected value [null]; codes [NotNull.accountMaintenanceSave.nAccountId,NotNull.nAccountId,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [accountMaintenanceSave.nAccountId,nAccountId]; arguments []; default message [nAccountId]]; default message [Account id can not be null]] ",
      "error": "org.springframework.web.bind.MethodArgumentNotValidException",
      "path": "/spacestudy/rockefeller/admin/account/updateAccountData"
    }
    

    message 存档我只能打印吗 [Account id can not be null] ?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Phenomenal One    6 年前

    试试这个。

    @ControllerAdvice
    public class RestExceptionHandler { 
    
        @ExceptionHandler(Exception.class)
        public ResponseEntity<Object> handleAllExceptionMethod(Exception ex, WebRequest requset) {
    
        ExceptionMessage exceptionMessageObj = new ExceptionMessage();
    
        // Handle All Field Validation Errors
        if(ex instanceof MethodArgumentNotValidException) {
            StringBuilder sb = new StringBuilder(); 
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors();
            for(FieldError fieldError: fieldErrors){
                sb.append(fieldError.getDefaultMessage());
                sb.append(";");
            }
            exceptionMessageObj.setMessage(sb.toString());
        }else{
            exceptionMessageObj.setMessage(ex.getLocalizedMessage());
        }
    
        exceptionMessageObj.setError(ex.getClass().getCanonicalName());
        exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());
    
        // return exceptionMessageObj;
        return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
    
        2
  •  0
  •   dnny    6 年前

    把你的 只有 要捕获Exception.Class的ExceptionHandler使其成为ConstraintIOllationException.Class

        3
  •  0
  •   Phenomenal One    6 年前

    你能试试下面的代码吗?

    import javax.validation.constraints.NotNull;
    
    public class AccountMaintenanceSave { 
    
    @NotNull(nullable=false,message="Account id can not be null")
    public Integer nAccountId;
    @NotNull
    public String sClientAcctId;
    @NotNull
    public String sAcctDesc;
    @NotNull
    public String sLocation;
    @NotNull
    public Integer nDeptId; 
    @NotNull
    public Integer nAccountCPCMappingid;
    @NotNull
    public Integer nInvestigatorId;
    
    //Getter and Setter
    }