【问题标题】:Custom messages for SpringBoot RESTful bean validation not workingSpring Boot RESTful bean 验证的自定义消息不起作用
【发布时间】:2017-02-12 23:55:42
【问题描述】:

我在@RestController 中添加了一个验证(@javax.validation.Valid),并在@RequestBody 类中使用了@NotEmpty 注释:

public class Invoice {

    @NotEmpty
    private String commentText;

    // omitted
}

当调用缺少 commentText 的 REST 调用时,会向客户端返回正确的错误:

{
   "timestamp": 1475599494823,
   "status": 400,
   "error": "Bad Request",
   "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
   "errors": [   {
      "codes":       [
         "NotEmpty.invoice.commentText",
         "NotEmpty.commentText",
         "NotEmpty.java.lang.String",
         "NotEmpty"
      ],
      "arguments": [      {
         "codes":          [
            "invoice.commentText",
            "commentText"
         ],
         "defaultMessage": "commentText",
         "code": "commentText"
      }],
      "defaultMessage": "may not be empty",
      "objectName": "invoice",
      "field": "commentText",
      "bindingFailure": false,
      "code": "NotEmpty"
   }],
   "message": "Validation failed for object='invoice'. Error count: 1",
   "path": "/api/invoices/1"
}

然后我创建了具有以下内容的 src/main/resources/messages.properties

NotEmpty.invoice.commentText=Please type a comment

问题是返回给客户端的是原始错误消息,而不是自定义的“请输入评论”。

我正在使用带有 YAML 配置的 SpringBoot 1.4 并在 Eclipse 中运行应用程序。

知道问题出在哪里吗?

【问题讨论】:

  • 有关于这个问题的更新吗?

标签: java spring spring-boot bean-validation


【解决方案1】:

尝试使用javax.validation 包中的替代方案,而不是@NotEmptyannotation:@NotNull@Size(min=1)。 此外,您可能会发现此示例项目对您有用:https://github.com/MichaelKnight/ValidandoFormularios

如果由于某种原因您需要使用@NotEmpty 注解,那么您应该创建一个文件 ValidationMessages.properties 并将其放入您的类路径中。

为避免密钥转换出现问题,您可以这样指定消息密钥:@NotEmpty(message="{NotEmpty.invoice.commentText}")。或者看看这里: http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html#section-message-interpolation

【讨论】:

  • 我在messages.properties 中尝试了@javax.validation.constraints.NotNullNotNull.unidentifiedInvoice.commentText=Please type a comment,但它仍然返回默认的"defaultMessage": "may not be null"
  • 您是否已将班级名称更改为 UnidentifiedInvoice?如果不尝试使用此密钥:NotNull.invoice.commentText.
  • 对不起,是的,我做到了……但这不是问题的根本原因。
猜你喜欢
  • 2011-12-24
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
相关资源
最近更新 更多