我正在使用Bean验证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"
?
您必须使用MessageSource bean和消息。属性文件,你可以像下面这样添加键值。
typeMismatch=Please use MM/dd/yyyy format
如果你使用的是SpringBoot,那么默认情况下MessageSource bean是可用的,你只需要在messages.properties中添加key-value。对于普通的Spring应用,你可以使用ReloadableResourceBundleMessageSource或ResourceBundleMessageSource。
属性键按以下顺序解析。
typeMismatch.[form].[property]
typeMismatch.[form]
typeMismatch
请参考http://jtuts.com/2014/11/09/validating-dates-in-spring-form-objects/
添加自定义错误消息的正确方法是通过DefaultMessageCodeResolver你可以使用解析器在对象+字段级别绑定错误(typeMismatch.YourClassName)。生日=自定义消息),如javadoc.
所述。在这里找到详细的用法