2011-04-21 243 views
3

我正在使用Spring 3.0.5-RELEASE,JSR-303樣式驗證和Hibernate驗證程序4.1.0-Final。我的模型類看起來是這樣的:JSR-303驗證與自定義消息

public class Model { 
    @Max(value=10,message="give a lower value") 
    Integer n; 
} 

這是作爲請求參數在一個spring mvc servlet中綁定傳遞的。因此,請求將是這個樣子:

http://localhost:8080/path?n=10

我要的是能夠自定義錯誤信息時,有一個類型不匹配的異常,例如

http://localhost:8080/path?n=somestring

這導致我想更換一個很長的默認消息。

我已經嘗試過幾乎所有在網絡上描述的配置,而且它們都不起作用。有人知道什麼是正確的配置嗎?

具體來說,我需要在我的mvc-servlet.xml中做什麼?我在我的messages.properties文件中需要什麼? message.properties文件是否有一個神奇的名字,以便hibernate-validator能夠找到它?

我用我的MVC-servlet.xml中沒有成功如下:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:basename="messages" /> 

而一個messages.properties文件在的src/main /資源(以及在SRC /主/ web應用/ WEB -INF)...

我試過各種各樣的messages.properties中的組合,即使做簡單的覆蓋說@NotEmpty消息,甚至不適用於我。

+0

我也有這個問題。 「非常長的默認消息」就像「Property myRequest.grossAmount引發異常;嵌套異常是java.lang.IllegalArgumentException」 – 2012-04-18 20:21:40

+0

請參閱http://stackoverflow.com/a/36344999/1030527解決方案,甚至提供驗證字段名稱。 – bernie 2016-04-01 17:00:11

回答

8

錯誤消息需要進入名爲ValidationMessages.properties的文件。只要把它放在你的classpath中的hibernate jars之前。

例如,如果你有一個ValidationMessages.properties文件,其中包含以下屬性:

email_invalid_error_message=Sorry you entered an invalid email address 
email_blank_error_message=Please enter an email address 

然後你可以有以下約束的域對象:

public class DomainObject{ 
... 
@Email(message = "{email_invalid_error_message}") 
@NotNull(message = "{email_blank_error_essage}") 
@Column(unique = true, nullable = false) 
String primaryEmail; 
... 
} 
1

我要的是能夠在存在類型不匹配異常時自定義錯誤消息,例如

據我所知,這個消息由Spring MVC生成,而不是由Hibernate Validator生成。我建議以下行添加到messages.properties文件:

typeMismatch.java.lang.Integer=Must specify an integer value 
4

我在另一個問題找到了答案,這和它的工作對我來說: spring 3.0 MVC seems to be ignoring messages.properties

混亂的部分給我,因爲我是新來的春天,我希望能夠把消息放在ValidationMessages.properties中。但是,這個錯誤發生在綁定時,在驗證之前。因此,不要使用ValidationMessages.properties,而是使用常規的ResourceBundle messages.properties文件。

把這個在您的?? - servlet.xml文件:

<bean id="messageSource" 
class="org.springframework.context.support.ResourceBundleMessageSource"> 
    <property name="basename" value="messages"/> </bean> 

認沽行像這些在你的messages.properties文件。

typeMismatch.myRequest.amount=Amount should be a number. 
methodInvocation.myRequest.amount=Amount should be a number. 

在本例中,myRequest是我的表單模型,而amount是該表單中的一個屬性。 typeMismatch和methodInvocation是預定義的,並且對應於綁定/轉換異常,比如您似乎正在獲取的綁定/轉換異常。我很難爲它們或值列表找到好的文檔,但是我發現它們對應於某些Spring異常中的ERROR_CODE常量。 http://static.springsource.org/spring/docs/2.5.x/api/constant-values.html#org.springframework.beans.MethodInvocationException.ERROR_CODE

我把這個項目的messages.properties文件放在我的源文件夾的根目錄下,這個文件夾放在我的類路徑的根目錄中,同時還有ValidationMessages.properties。

0

問題是數據綁定錯誤消息,而不是驗證錯誤消息。有足夠的答案here