java Spring验证器检查重复项后从bindingResult获取null?

pod7payv  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(132)

下面是我的简单的传感器配准控制器方法。

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

传感器验证类。这里我认为.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","This name is already taken");

    }
}

如果我试图创建双值,则响应如下

{
    "message": null,
    "timestamp": 1678379316410
}

responce值必须从.rejectvalue()方法中给予我默认的错误消息,我已经尝试了所有的错误方法。此外,如果我创建了一个空名称的传感器,它会传递它,即使我写了@Size(min=1)和@NotEmpty注解。所以我归咎于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 [This name is already taken]
这个默认消息我正试图得到我的json响应

wpx232ag

wpx232ag1#

我已经解决了这个问题,主要的问题是理解bindingresult不能做json响应,所以我改变了我的验证方法,抛出我自己的自定义异常,并将其转换为json with

@Override
public void validate(Object target, Errors errors) {
    Sensor sensor = (Sensor) target;
    if (sensorService.getName(sensor.getName()).isPresent())
        throw new DoubleSensorNameError();

}

这是我的控制器类,我在其中创建了exceptionhandler类来生成JSON

@ExceptionHandler
private ResponseEntity<SensorErrorResponse> handleException(DoubleSensorNameError e){
    SensorErrorResponse errorResponse = new SensorErrorResponse(
            "Duplicate sensor name",System.currentTimeMillis()
    );
    return new ResponseEntity<>(errorResponse,HttpStatus.NOT_FOUND);
}

相关问题