简体   繁体   中英

JSR-303 and Spring MVC Binding Result

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM