英文:
Getting null from bindingResult after Spring Validator checks duplicates?
问题
这是我的简单注册传感器的控制器方法。
@PostMapping("/registration")
public ResponseEntity<HttpStatus> create(@RequestBody @Valid SensorDTO sensorDTO,
BindingResult bindingResult){
//这个响应的值是null!
sensorValidator.validate(convertToSensor(sensorDTO), bindingResult);
if (bindingResult.hasErrors()){
StringBuilder errorMessage = new StringBuilder();
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors){
errorMessage
.append(error.getDefaultMessage());
}
throw new SensorNotCreatedException(errorMessage.toString());
}
sensorService.save(convertToSensor(sensorDTO));
return ResponseEntity.ok(HttpStatus.OK);
}
传感器验证类。我认为.rejectvalue()
方法有问题。
@Component
public class SensorValidator implements Validator {
private final SensorService sensorService;
@Autowired
public SensorValidator(SensorService sensorService) {
this.sensorService = sensorService;
}
@Override
public boolean supports(Class<?> clazz) {
return Sensor.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Sensor sensor = (Sensor) target;
if (sensorService.getName(sensor.getName()).isPresent())
errors.rejectValue("name","45234","这个名字已经被使用了");
}
}
这是当我尝试创建双重值时的响应。
{
"message": null,
"timestamp": 1678379316410
}
响应值应该给我.rejectvalue()
方法的默认错误消息,我已经尝试了所有的错误方法。此外,如果我创建一个空名称的传感器,它会通过,即使我写了@Size(min=1)
和@NotEmpty
注解。所以我怀疑是bindingresult
类有问题。
当我将bindingresult
打印到控制台时,会发生以下情况。
org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'sensorDTO' on field 'name': rejected value [Mega Cool sensor]; codes [45234.sensorDTO.name,45234.name,45234.java.lang.String,45234]; arguments []; default message [这个名字已经被使用了]
我正试图将这个默认消息添加到我的JSON响应中。
英文:
Here is my simple registration controller method for Sensor.
@PostMapping("/registration")
public ResponseEntity<HttpStatus> create(@RequestBody @Valid SensorDTO sensorDTO,
BindingResult bindingResult){
//This one responses with null value !
sensorValidator.validate(convertToSensor(sensorDTO), bindingResult);
if (bindingResult.hasErrors()){
StringBuilder errorMessage = new StringBuilder();
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors){
errorMessage
.append(error.getDefaultMessage());
}
throw new SensorNotCreatedException(errorMessage.toString());
}
sensorService.save(convertToSensor(sensorDTO));
return ResponseEntity.ok(HttpStatus.OK);
}
Sensor Validation class. Here i think something is wrong with .rejectvalue() method.
@Component
public class SensorValidator implements Validator {
private final SensorService sensorService;
@Autowired
public SensorValidator(SensorService sensorService) {
this.sensorService = sensorService;
}
@Override
public boolean supports(Class<?> clazz) {
return Sensor.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Sensor sensor = (Sensor) target;
if (sensorService.getName(sensor.getName()).isPresent())
errors.rejectValue("name","45234","This name is already taken");
}
}
here is the responce if i try to create double values
{
"message": null,
"timestamp": 1678379316410
}
The responce value have to give me the defailt error message from .rejectvalue() method and i've tryied all error methods. Also if i create a Sensor with empty name it passes it, even if i wrote @Size(min=1) and @NotEmpty annotations. So i blame on bindingresult- something wrong with this class
Here what happens if i pring the bindingresult to console
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'sensorDTO' on field 'name': rejected value [Mega Cool sensor]; codes [45234.sensorDTO.name,45234.name,45234.java.lang.String,45234]; arguments []; default message [This name is already taken]
This defalut message i'am trying to get to my json responce
答案1
得分: 0
我已经解决了这个问题。主要问题是要理解BindingResult不能执行JSON响应。因此,我已经更改了我的验证方法,将其更改为抛出我的自定义异常,并将其转换为JSON,如下所示:
@Override
public void validate(Object target, Errors errors) {
Sensor sensor = (Sensor) target;
if (sensorService.getName(sensor.getName()).isPresent())
throw new DoubleSensorNameError();
}
这是我的控制器类,我在其中创建了一个异常处理程序类以生成JSON响应:
@ExceptionHandler
private ResponseEntity<SensorErrorResponse> handleException(DoubleSensorNameError e){
SensorErrorResponse errorResponse = new SensorErrorResponse(
"Duplicate sensor name", System.currentTimeMillis()
);
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
如您所需,我已经将代码部分翻译成中文。
英文:
I've solved that. The main problem was to understand that bindingresult can't do json respond.
So i've changed my validation method to throw my own custom exception and trasform it to json with
@Override
public void validate(Object target, Errors errors) {
Sensor sensor = (Sensor) target;
if (sensorService.getName(sensor.getName()).isPresent())
throw new DoubleSensorNameError();
}
This is my conroller class where i created exceptionhandler class to generate json
@ExceptionHandler
private ResponseEntity<SensorErrorResponse> handleException(DoubleSensorNameError e){
SensorErrorResponse errorResponse = new SensorErrorResponse(
"Duplicate sensor name",System.currentTimeMillis()
);
return new ResponseEntity<>(errorResponse,HttpStatus.NOT_FOUND);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论