问题
I'm trying to figure out how to get localized error messages when a validation error occurs.
My domain object looks like this:
@RooJavaBean
@RooToString
@RooEntity
public class Lead {
@Email(message = "{email_error_message}")
String emailAddress;
}
My Controller looks like this:
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody String create(@Valid Lead lead, BindingResult result) {
log.debug("In POST!");
if(result.hasErrors())
{
FieldError fieldError = result.getFieldError("emailAddress");
return fieldError.getDefaultMessage();
}
else
{
log.debug("Email = " + lead.getEmailAddress());
try
{
lead.persist();
lead.flush();
}
catch(DataAccessException ex)
{
log.debug("Oh OH...");
return "Sorry we are experiencing technical difficulties, please try again later";
}
return "";
}
}
I also created ValidationMessages.properties.
email_error_message=Sorry your email is invalid
In my webmvc-config.xml :
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource"
p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application" p:fallbackToSystemLocale="false"/>
The error I get from fieldError.getDefaultMessage() is {email_error_message}. So the question is what am I wrong?
回答1:
I'm not sure how to get message
attribute work with Spring message sources, too.
However, you can always use default message code (see DefaultMessageCodesResolver):
Email.lead.emailAddress=Sorry your email is invalid
回答2:
In your webmvc-config.xml, you're loading properties from application.properties.
If your ValidationMessages.properties is in the same dir, try loading it like this:
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource"
p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application,WEB-INF/i18n/messages,WEB-INF/i18n/ValidationMessages" p:fallbackToSystemLocale="false"/>
The other thing is if you have a webapp which users are picking locale, you don't want the message from the local runtime. You want to get the user's session locale and use that to do the localization.
来源:https://stackoverflow.com/questions/5073488/jsr-303-and-spring-mvc-binding-result