使用@valid where/how自定义错误消息进行春季验证 [英] spring validation with @valid where/how custom error messages
问题描述
我正在尝试使用属性文件中的错误消息进行一些Spring验证. 但是我发现所有示例似乎都对值进行了硬编码,或者从属性文件中获取了值,但使用了Validator类并在那里进行了检索.
I'm trying to do some spring validation with the error messages in properties files. But the examples I find all seem to have the values hardcoded, or gotten from a properties file but using a validator class and retrieving it there.
我的设置有些不同. 我在requestmapping中使用@Valid批注,而我的@Valid类使用@NotNull等. 我看过一些人在做@NotNull(message ="blablabla");的例子. 但这也是经过硬编码的,我想将消息放入属性文件中,以便我可以轻松地对其进行即时编辑,以便将来可以轻松实现i18n.
My setup is a bit different. I'm using the @Valid annotation in my requestmapping, and my @Valid class uses @NotNull etc. I've seen some examples where people do @NotNull(message = "blablabla"); But that's also hardcoded, and I'd like to put the messages in a properties file so I can easily edit it on the fly and so I can easily implement i18n in the future.
对于如何实现这一目标的任何投入,我们将不胜感激.
Any input on how to achieve this would be appreciated.
推荐答案
It works exactly the same way as with explicit Validator
- you declare a MessageSource
and write error messages in .properties
files. Messages codes are formed as constraintName.modelAttributeName.propertyName
:
publib class Foo {
@NotNull private String name;
...
}
.
@RequestMapping
public String submitFoo(@Valid Foo foo, ...) { ... }
messages.properties
:
NotNull.foo.name=...
MessageSource
声明:
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value = "messages" />
</bean>
这篇关于使用@valid where/how自定义错误消息进行春季验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!