具有自定义消息的JSR-303验证 [英] JSR-303 validation with custom message

查看:130
本文介绍了具有自定义消息的JSR-303验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Spring 3.0.5-RELEASE, with JSR-303 style validation and Hibernate validator 4.1.0-Final. My model class looks something like this:

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

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

And this is passed as request param in a spring mvc servlet with binding. So the request would look something like this:

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

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

What I want is to be able to customize the error message when there is a type mismatch exception, e.g.

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

这会导致我要替换的很长的默认消息.

Which results in a very long default message that I want to replace.

我已经尝试了几乎所有在网络上描述的配置,但它们似乎都不起作用.有人知道什么是正确的配置吗?

I've tried just about every configuration described on the web and none of them seem to work. Does someone know what the right configuration is?

具体来说,我的mvc-servlet.xml需要什么?我的messages.properties文件中需要什么? message.properties文件是否具有魔术名称,以便hibernate-validator可以找到它?

Specifically, what do I need in my mvc-servlet.xml? What do I need in my messages.properties file? Does the message.properties file have a magic name so that hibernate-validator will find it?

我在我的mvc-servlet.xml中使用了以下命令,但未成功:

I've used the following in my mvc-servlet.xml without success:

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

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

And a messages.properties file at src/main/resources (and also at src/main/webapp/WEB-INF)...

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

I've tried all sorts of combinations in messages.properties even for doing simple override of say @NotEmpty messages and even that doesn't work for me.

推荐答案

错误消息需要放入名为ValidationMessages.properties的文件中.只需将其放在休眠jar之前的类路径中的某个位置即可.

Error messages need to go into a file named ValidationMessages.properties. Just put that somewhere in your classpath before the hibernate jars.

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

For example if you have a ValidationMessages.properties file that contains the following properties:

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

然后,您可能具有以下约束的域对象:

Then you could have a domain object with the following constraints:

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

这篇关于具有自定义消息的JSR-303验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆