【问题标题】:Spring Boot 2.1.5: Failed to replace {0} with Field Name on Validation MessageSpring Boot 2.1.5:无法在验证消息中将 {0} 替换为字段名称
【发布时间】:2019-10-25 09:15:53
【问题描述】:

我正在尝试将 spring-boot 2.1.4 升级到 2.1.5。

在 spring-boot 2.1.4 中,带有 {0} 参数的自定义验证错误消息正确替换为字段名称。 但是 spring-boot 2.1.5,验证错误消息显示为 {0}。

代码

  • messages.properties
notblank={0} must not be blank
  • 人员表单
import javax.validation.constraints.NotBlank;

class PersonForm {

    @NotBlank(message = "{notblank}")
    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "Person(Name: " + this.name + ")";
    }
}

这是我的示例项目。
https://github.com/spikefin-goby/spring-boot-validation-sample

spring-boot 2.1.4 结果

在spring-boot 2.1.4中,显示「name不能为空」
(正确地将 {0} 替换为字段名称)
spring-boot 2.1.4 validation message

BingingResult.errors[0] 是FieldError


spring-boot 2.1.5 结果

但是spring-boot 2.1.5,显示「{0}不能为空
spring-boot 2.1.5 validation message

BingingResult.errors[0] 是LocalValidatorFactoryBean


对此我能做些什么?


更新

Spring Boot 2.1.6 已于 2019 年 6 月 19 日发布。 此问题已解决!

在spring-boot 2.1.6中,显示「name不能为空」
(正确地将 {0} 替换为 Field Name )

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

    在我看来,你在 spring-context-5.1.7 中遇到了issue #23014: validation error message {0} is not working

    【讨论】:

    • 感谢您提供的信息。@Lesiak 我将等待 spring-context-5.1.8。同时我会考虑修复这段代码。
    【解决方案2】:

    您可以使用这样的异常处理程序来做到这一点:

    public ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex) {
        List<String> errors = new ArrayList<>();
        for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
            String error = String.format("%s.%s: %s", violation.getRootBeanClass().getSimpleName(),
                    violation.getPropertyPath(), violation.getMessage());
            errors.add(error);
            logger.error(error);
        }
    
        ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, errors);
        return new ResponseEntity<>(apiError, new HttpHeaders(), apiError.getStatus());
    }
    

    violation.getPropertyPath() 返回引发违规的字段的名称。

    附带说明:我正在使用我的自制课程ApiError 来显示错误。您不需要这样做,但重要的是您在 ConstraintViolationException 中迭代约束违规以获取它们每个的属性路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 2021-07-17
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多