使用自定义消息进行JSR-303验证

Kev*_*vin 4 spring-mvc hibernate-validator bean-validation

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

这在带有绑定的spring mvc servlet中作为请求参数传递.所以请求看起来像这样:

HTTP://本地主机:8080 /路径N = 10

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

HTTP://本地主机:8080 /路径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" />
Run Code Online (Sandbox Code Playgroud)

并在src/main/resources(以及src/main/webapp/WEB-INF)上的messages.properties文件...

我已经在messages.properties中尝试过各种各样的组合,甚至可以简单地覆盖@NotEmpty消息,甚至对我来说也不行.

Kar*_*ran 8

错误消息需要进入名为的文件ValidationMessages.properties.只需将它放在hibernate jar之前的类路径中.

例如,如果您有一个ValidationMessages.properties包含以下属性的文件:

email_invalid_error_message=Sorry you entered an invalid email address
email_blank_error_message=Please enter an email address
Run Code Online (Sandbox Code Playgroud)

然后你可以拥有一个具有以下约束的域对象:

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


k-d*_*den 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>
Run Code Online (Sandbox Code Playgroud)

将这些行放在您的 messages.properties 文件中。

typeMismatch.myRequest.amount=Amount should be a number.
methodInvocation.myRequest.amount=Amount should be a number.
Run Code Online (Sandbox Code Playgroud)

在这个例子中,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 放在我的源文件夹的根目录中,该文件夹将它放在我的类路径的根目录中。