spring validation with @valid where/how custom error messages

不打扰是莪最后的温柔 提交于 2019-11-28 05:35:01

问题


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.

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.


回答1:


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 declaration:

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value = "messages" />
</bean>


来源:https://stackoverflow.com/questions/4281165/spring-validation-with-valid-where-how-custom-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!