从Spring验证器检查重复项后,bindingResult返回null吗?

huangapple go评论140阅读模式
英文:

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(&quot;/registration&quot;)
    public ResponseEntity&lt;HttpStatus&gt; 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&lt;FieldError&gt; 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&lt;?&gt; 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(&quot;name&quot;,&quot;45234&quot;,&quot;This name is already taken&quot;);

    }
}

here is the responce if i try to create double values

{
    &quot;message&quot;: null,
    &quot;timestamp&quot;: 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 &#39;sensorDTO&#39; on field &#39;name&#39;: 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&lt;SensorErrorResponse&gt; handleException(DoubleSensorNameError e){
    SensorErrorResponse errorResponse = new SensorErrorResponse(
            &quot;Duplicate sensor name&quot;,System.currentTimeMillis()
    );
    return new ResponseEntity&lt;&gt;(errorResponse,HttpStatus.NOT_FOUND);
}

huangapple
  • 本文由 发表于 2023年3月10日 00:37:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定