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

| 我使用的是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消息,即使这样对我也不起作用。     
已邀请:
错误消息需要进入名为“ 2”的文件。只需将其放在休眠jar之前的类路径中的某个位置即可。 例如,如果您有一个包含以下属性的“ 2”文件:
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;
...
}
    
我在另一个问题中找到了答案,它对我有用: Spring 3.0 MVC似乎忽略了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一起放在源文件夹的根目录中,并将其放在我的类路径的根目录中。     
  我想要的是能够在存在类型不匹配异常时自定义错误消息,例如 据我了解,该消息是由Spring MVC而非Hibernate Validator生成的。我建议在
messages.properties
文件中添加以下行:
typeMismatch.java.lang.Integer=Must specify an integer value
    
问题是针对数据绑定错误消息,而不是验证错误消息。这里有一个适当的答案。     

要回复问题请先登录注册