【问题标题】:How to add custom error message in org.springframework.format.annotation.DateTimeFormat?如何在 org.springframework.format.annotation.DateTimeFormat 中添加自定义错误消息?
【发布时间】:2016-09-29 19:55:23
【问题描述】:

我正在使用 Bean Validation API 和我的自定义消息进行表单验证:

@NotNull(message = "Please enter your birthday.")
@DateTimeFormat(pattern = "MM/dd/yyyy")
@Past(message = "That's impossible.")
private Date birthday;

在我输入错误的日期格式之前一切正常。然后我在我的页面上收到了如此冗长而冗长的错误消息:

Failed to convert property value of type [java.lang.String] to required type
[java.util.Date] for property birthday; nested exception is
bla-bla-bla...

由于org.springframework.format.annotation.DateTimeFormat 中的@interface DateTimeFormat 中没有字段message,因此我无法像使用其他注释那样在其中添加消息。

如何在此处指定"Please use MM/dd/yyyy format" 之类的自定义消息?

【问题讨论】:

  • 请注意,您看到的是转换,而不是验证错误。只有在使用从 String 转换的值初始化 bean 后,验证才会启动。

标签: java spring validation


【解决方案1】:

您必须使用 MessageSource bean 和 messages.properties 文件,您可以在其中添加如下键值。

typeMismatch=Please use MM/dd/yyyy format

如果您使用的是 SpringBoot,那么 MessageSource bean 将默认可用,您只需在 messages.properties 中添加键值。对于普通的 Spring 应用程序,您可以使用 ReloadableResourceBundleMessageSource 或 ResourceBundleMessageSource。

按以下顺序解析属性键。

typeMismatch.[form].[property] 
typeMismatch.[form]
typeMismatch

请参考http://jtuts.com/2014/11/09/validating-dates-in-spring-form-objects/

【讨论】:

  • 我已经有了这个 bean 和文件,我在问题中跳过了这个以简化它。顺便说一句,message.properties 只是为了方便而将消息外部化到单独的文件中。好的,在实体类中将这个typeMismatch 属性指向哪里?
  • 你不需要指向这个键。注释 @DateTimeFormat 将自动从 message.properties 文件中获取键值。我已经更新了我的答案。请看。
  • 不客气。如果它解决了您的问题,请不要忘记接受答案。这对其他人会有所帮助。
【解决方案2】:

添加自定义错误信息的正确方法是通过DefaultMessageCodeResolver 您可以使用解析器在对象 + 字段级别(typeMismatch.YourClassName.birthday = custom message.)绑定错误,如 javadoc 中所述。

查找详细用法here

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2020-11-13
    • 2017-05-30
    • 2023-01-05
    相关资源
    最近更新 更多