2011-04-21 148 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