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

时间:2018-09-18 12:09:23

标签: java validation spring-data-jpa

我正在使用spring data JPA创建应用程序。在这种情况下,我试图使用注释实现服务器端验证。我在带有自定义消息的字段上添加了@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 个答案:

答案 0 :(得分:1)

尝试一下。

@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);
  }
}

答案 1 :(得分:0)

让您的 only ExceptionHandler捕获Exception.class使其成为ConstraintViolationException.class

答案 2 :(得分:0)

您可以尝试以下代码吗?

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
}