【问题标题】:Why a validation message is not replaced in Spring Boot?为什么在 Spring Boot 中没有替换验证消息?
【发布时间】:2019-12-23 13:14:37
【问题描述】:

现在我使用 Spring Boot 开发了 REST API。

我尝试验证路径参数并使用这样的自定义消息处理异常。

FooController.java

@Validated
@RestController
@RequiredArgsConstructor
public class FooController {

  private final BarService service;

  @GetMapping(value = "/test/{id}")
  public void invoke(@PathVariable @Digits(integer = 10, fraction = 0, message = "{message}") Long id) {
    service.get(id);
    ...
  }
}

ApiExceptionHandler.java

@RestControllerAdvice
@RequiredArgsConstructor
public class ApiExceptionHandler {

  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException exception) {
    Map<String, String> messages = new HashMap<>();
    for (ConstraintViolation violation : exception.getConstraintViolations()) {
      messages.put("message", violation.getMessage());
    }
    return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST);
  }
}

ValidationMessages.properties

message={0} must not be more than {integer} digits

当我调用这个 API 超过 10 位时(例如,[GET /test/12345678901])发生 400 错误。

我的预期反应是

{
  message : id must not be more than 10 digits
}

但是,实际的反应是

{
  message : {0} must not be more than 10 digits
}

所以,我的问题是“为什么不替换验证消息”。

如果这种方法是错误的,那么有什么方法可以得到预期的响应吗?

感谢您阅读我的问题。

附录 使用的 Spring Boot 版本是 2.1.1

【问题讨论】:

    标签: java spring spring-boot exception path-variables


    【解决方案1】:

    必须使用${validatedValue}获取消息中的参数:

    message=${validatedValue} must not be more than {integer} digits
    

    请在文档中了解有关消息插值的更多信息:

    https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1#section-interpolation-with-message-expressions

    【讨论】:

    • 感谢您的快速响应和共享文档链接。我使用了 ${validatedValue},但响应如下。 { message : 12345678001 must not be more than 10 digits } ${validatedValue} 被替换为值(12345678901),而不是键(id)。这不是我想要得到的。我将从文档中调查更多信息。非常感谢您的回答。
    • 哦,我明白了。我很抱歉造成误解。您可以编写自己的 MessageInterpolator。在那里您可以访问所有信息:docs.jboss.org/hibernate/stable/validator/reference/en-US/…
    • 感谢您的好意。我将尝试编写自己的 MessageInterpolator。感谢您的支持。
    猜你喜欢
    • 2019-10-25
    • 2014-01-04
    • 2018-01-23
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多