JSR-303 and Spring MVC Binding Result

血红的双手。 提交于 2020-01-16 04:09:12

问题


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

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