Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

spring validation with @valid where/how custom error messages

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...