2016-09-29 77 views
1

我正在使用Bean驗證API一個表單驗證我的自定義消息:如何在org.springframework.format.annotation.DateTimeFormat中添加自定義錯誤消息?

@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... 

由於沒有現場message@interface DateTimeFormatorg.springframework.format.annotation.DateTimeFormat,我不能有加我的消息我與其他註釋一樣。

如何在那裏指定自定義消息,如"Please use MM/dd/yyyy format"

回答

3

您將不得不使用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/

+0

我已經有這個bean和文件,我在這個問題跳過這個簡化它。 Btw'message.properties'只是爲了方便而將消息外化到一個單獨的文件。好吧,在實體類中指向'typeMismatch'屬性的位置? – DimaSan

+0

你不需要指出這個鍵。註釋@DateTimeFormat將自動從message.properties文件中獲取鍵值。我已經更新了我的答案。請參見。 – abaghel

+0

謝謝,我今晚會試一試。 – DimaSan

2

正確的方法來添加自定義錯誤消息是通過DefaultMessageCodeResolver 您可以使用解析綁定的對象+現場級的錯誤(typeMismatch.YourClassName.birthday =自定義消息。)正如javadoc中提到的那樣。

查找詳細的使用here

相關問題