Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

spring mvc - JSR-303 validation with custom message

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;
}

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?

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?

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

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

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

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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;
...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...