2015-06-15 65 views
3

在Spring中,如何覆蓋默認的窗體錯誤按摩?覆蓋彈出窗體的錯誤消息

我正在使用Validator和一個屬性文件來添加我自己的錯誤消息,但是 如何覆蓋在轉換​​/編碼錯誤上打印的消息,例如?

他們似乎自動生成的,我不認爲有利於用戶:

Failed to convert property value of type java.lang.String to required type java.lang.Double for property minPrice; nested exception is java.lang.NumberFormatException: 
+1

根據以下規則在屬性文件中定義消息以覆蓋默認值:http://stackoverflow.com/a/27725232/1291150 –

+0

非常感謝。如果你想讓你的評論成爲一個答案,那麼我可以接受它。 – GionJh

回答

5

你可以在你的本地化包與以下由Spring的DefaultMessageCodeResolver中定義的約定密鑰創建自定義消息覆蓋默認值。爲了完整這裏起見是它的文檔的相關部分:

將創建一個對象錯誤兩個消息碼,在下面的 順序(使用前綴格式化時):

1.: code + "." + object name 
2.: code 

將創建四個消息的代碼字段規範,在 順序如下:

1.: code + "." + object name + "." + field 
2.: code + "." + field 
3.: code + "." + field type 
4.: code 

例如,在代碼「typeMismatch」的情況下,對象名「用戶」,字段 ‘年齡’:

1. try "typeMismatch.user.age" 
2. try "typeMismatch.age" 
3. try "typeMismatch.int" 
4. try "typeMismatch" 

這種分辨率算法從而可以利用例如顯示 特定消息爲綁定錯誤像‘需要’和 ‘typeMismatch’:

at the object + field level ("age" field, but only on "user"); 
at the field level (all "age" fields, no matter which object name); 
or at the general level (all fields, on any object). 

在數組,列表或地圖屬性的情況下,生成特定的 元素和整個集合的代碼。假設對象「用戶」陣列「基團」的字段 「姓名」:

1. try "typeMismatch.user.groups[0].name" 
2. try "typeMismatch.user.groups.name" 
3. try "typeMismatch.groups[0].name" 
4. try "typeMismatch.groups.name" 
5. try "typeMismatch.name" 
6. try "typeMismatch.java.lang.String" 
7. try "typeMismatch" 

默認情況下,ErrorCode的將被放置在的 構造消息字符串的開頭。 messageCodeFormatter屬性可以是 ,用於指定替代級聯格式。

爲了將所有代碼分組到您的 資源包中的特定類別,例如, 「validation.typeMismatch.name」而不是 默認的「typeMismatch.name」,請考慮指定應用的前綴爲 。