5

我正在使用 Spring 3.0.5-RELEASE,带有 JSR-303 样式验证和 Hibernate 验证器 4.1.0-Final。我的模型类看起来像这样:

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" />

还有一个位于 src/main/resources(以及 src/main/webapp/WEB-INF)的 messages.properties 文件......

我已经尝试了 messages.properties 中的各种组合,即使只是简单地覆盖了@NotEmpty 消息,即使这对我也不起作用。

4

4 回答 4

8

错误消息需要进入一个名为ValidationMessages.properties. 只需将它放在你的类路径中的某个地方,放在休眠 jar 之前。

例如,如果您有一个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;
...
}
于 2011-04-25T18:27:51.683 回答
5

我在另一个问题中找到了答案,它对我有用: spring 3.0 MVC似乎正在忽略messages.properties

由于我是 Spring 新手,对我来说令人困惑的部分是我希望能够将消息放入 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 一起放在我的类路径的根目录中。

于 2012-04-19T20:04:28.080 回答
3

我想要的是能够在出现类型不匹配异常时自定义错误消息,例如

据我了解,这些消息是由 Spring MVC 生成的,而不是由 Hibernate Validator 生成的。我建议在文件中添加以下行messages.properties

typeMismatch.java.lang.Integer=Must specify an integer value
于 2011-06-25T04:43:07.897 回答
0

问题是针对数据绑定错误消息,而不是针对验证错误消息。这里有一个充分的答案。

于 2014-02-07T12:40:57.540 回答