gpt4 book ai didi

java - Spring Validation - 如何在我的 Controller 中检索 errors.rejectValue?

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:49 25 4
gpt4 key购买 nike

我的 TestValidator 中有我的验证方法,如下所示

@Override
public void validate(Object target, Errors errors) {
Test test = (Test) target;
String testTitle = test.getTestTitle();

//**ErrorCheck1** - This works, and I am able to pull the value in my controller
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "testTitle", "test.testTitle.projec", "My msg");


if (testTitle != null && testTitle.length() < 4) {
logger.error("Inside custom validation"+test.testTitle().length());

//**Error Check2**
//***HOW DO I RETRIEVE THE BELOW VALUE in My controller
errors.rejectValue(testTitle, "test.testTitle.lessThen4");
errors.addAllErrors(errors);
logger.error("Entered If condition of validate");
}
}

我的 Controller 是

@RequestMapping(value = "/test", method = RequestMethod.PUT)
public ResponseEntity<BasicResponseDTO> newTest(@Valid @RequestBody Test test, BindingResult result) {

if (result.hasErrors()){
logger.error("Entered Errors");
BasicResponseDTO basicResponseDTO = new BasicResponseDTO();
basicResponseDTO.setCode(ResponseCode.BAD_REQUEST);
return new ResponseEntity<BasicResponseDTO>(basicResponseDTO, HttpStatus.BAD_REQUEST);
}
}

当我的 ErrorCheck1 条件被激活时,我在 Controller 内的 IF 条件能够检索它。但是,在我的 ErrorCheck2 中,由于 errors.rejectValue 的原因,我立即在控制台上收到错误消息,并且无法正常处理 testTitle 长度小于 4 的情况。

What is the alternative to errors.rejectValue so that I may handle the error in my controller ?

最佳答案

好的 - 知道了。我所要做的就是改变

errors.rejectValue(testTitle, "test.testTitle.lessThen4");

errors.reject(testTitle, "test.testTitle.lessThen4");

RejectValue 是一个 Field 错误,本质上不是全局的。拒绝是一个全局错误,可以从 Controller 的错误列表中访问。

来自文档

void reject(String errorCode, String defaultMessage);
Register a global error for the entire target object, using the given error description.

@Override
public void validate(Object target, Errors errors) {
Test test = (Test) target;
String testTitle = test.getTestTitle();

//**ErrorCheck1** - This works, and I am able to pull the value in my controller
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "testTitle", "test.testTitle.projec", "My msg");


if (testTitle != null && testTitle.length() < 4) {
logger.error("Inside custom validation"+test.testTitle().length());

//**Error Check2**
//***HOW DO I RETRIEVE THE BELOW VALUE in My controller
errors.reject(testTitle, "test.testTitle.lessThen4");
errors.addAllErrors(errors);
logger.error("Entered If condition of validate");
}
}

希望对某人有所帮助。

关于java - Spring Validation - 如何在我的 Controller 中检索 errors.rejectValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com