如何在 Spring 中使用注释验证并从属性文件获取错误消息?
我是春天的新手。
我在我的域类中设置了验证,如下所示:
public class Worker {
@NotNull(message="Name must be input")
@Size(min=1,max=50, message="Name must not exceed 50 characters")
private String name;
...
}
这是 jsp 文件:
<form:input path="code" readonly="false" />
<font color="red"><form:errors path="code" />
控制器代码:
@RequestMapping(value="/test",method=RequestMethod.POST)
public void form(@Valid Worker worker, BindingResult result) {
if (result.hasErrors()) {
return;
}
...
它可以工作,但是如何在我的域中用一些文本(如worker.name.overflow)替换“名称不得超过50个字符”消息来源?我需要在 BindingResult 中添加 messageResolver 吗?
所有搜索结果似乎都在说编写自定义验证器类,但我现在想使用注释。我很确定有办法,因为在 这个问题 有人已经这么做了。
I'm a Spring newbie.
I set up validation in my domain class like this:
public class Worker {
@NotNull(message="Name must be input")
@Size(min=1,max=50, message="Name must not exceed 50 characters")
private String name;
...
}
Here's the jsp file:
<form:input path="code" readonly="false" />
<font color="red"><form:errors path="code" />
And the controller code:
@RequestMapping(value="/test",method=RequestMethod.POST)
public void form(@Valid Worker worker, BindingResult result) {
if (result.hasErrors()) {
return;
}
...
It works, but how can I replace "Name must not exceed 50 characters" with some text (like worker.name.overflow) in my messageSource? May I need to add a messageResolver into BindingResult?
All the search result seems to say about writing a custom Validator class, but I want to use annotation for now. I'm pretty sure there's a way, because in this question someone has done that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要告诉 Hibernate 验证器查找代码,请将消息的值放在大括号中,例如
@NotNull(message="{worker.name.NotNull}"
,然后将翻译放入 ValidationMessages .properties 位于类路径的根目录中(/WEB-INF/classes、Maven 中的资源文件夹等)。验证器实现会独立查找这些内容,并且它们会在已翻译的 BindingResult 上进行查找。作为默认消息发生在 Spring 消息源之外。理论上,您可以重写 LocalValidatorFactory bean,将验证器的消息输出作为代码放在 Errors 对象上,然后在注释中保留大括号,以便 Hibernate 验证器将其传递。将 JSR-303 ConstraintViolations 转换为 Spring Errors 的源代码非常简单,易于阅读和扩展,它只是将注释的名称作为代码,将注释属性作为 args,然后验证器的翻译作为默认消息,您可以阅读实现 此处。
您可以将
javax.validation.MessageInterpolator
添加到javax.validation.Configuration
中,告诉它在其他属性文件中查找消息。如果您使用 Spring LocalValidatorFactory bean,它上面有一个setMessageInterpolator()
,您可以使用它来注入一个。检查此源Hiberate 提供程序实现。To tell Hibernate validator to do a lookup on a code, put the value of message in braces, e.g.,
@NotNull(message="{worker.name.NotNull}"
, then put the translation in ValidationMessages.properties in the root of your classpath (/WEB-INF/classes, resources folder in Maven, etc.).The validator implementation looks those up independently on its own, and they go on the BindingResult already translated as the default message. Happens outside of the Spring messagesource. You could in theory override the LocalValidatorFactory bean to put the validator's message output onto the Errors object as the code and then leave the braces off in the annotation so that the Hibernate Validator passes it through. The source code that turns JSR-303 ConstraintViolations into Spring Errors is simple enough to read and extend. It just puts the name of the annotation on as code, the annotation properties as args, and then the validator's translation as the default message. You can read the implementation here.
You can add a
javax.validation.MessageInterpolator
to yourjavax.validation.Configuration
to tell it to look for messages in other properties files. If you're using the Spring LocalValidatorFactory bean, it has asetMessageInterpolator()
on it that you can use to inject one. Check this source for the Hiberate provider implementation.这是对问题的一点解释。
现在从验证标记中删除 { message = "Email size should be Between 1 and 50" } 。
完成此操作后,您的注释将如下所示。
现在在控制器端调试提交表单时调用的方法。下面是我的方法,当用户点击提交时接收请求。
现在将调试点放置在方法的第一行并调试参数“结果”。
在调试时,您会在代码数组中找到这样的字符串。
现在,在属性文件中定义该字符串,并根据该字符串定义一条消息。编译并执行。只要该注释未得到验证,就会显示该消息。
基本上,spring 将自己的字符串作为其属性文件消息的关键。在上面的键中
This is a bit explanation of problem.
Now remove { message = "Email size should be between 1 and 50" } from validation tag.
After doing this your annotation will be like this.
Now at controller side debug the method which is being called upon when submitting the form. Below is my method which is receiving the request when user hits submit.
Now place a debug point at very first line of the method and debug the argument "result".
While dubugging you will find a string like this in codes array.
Now define this string in your properties file and a message against that string. Compile and execute. That message will be displayed whenever that annotation wouldn't be validated.
Basically spring makes its own string as key to its property file message. In above key