How to get localized messages from properties file with error in bindResult?

Hi I have Ajax Forms

where I am using Async POST

to send data to the server ...

If BindingResult

has an error, I want to show a message in the field of view after the input field to explain the error, so this is my method in my controller:

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Map<String, String> create(@Valid MyClass myClass, BindingResult bindingResult, Model uiModel, 
        HttpServletRequest httpServletRequest, HttpServletResponse response, Locale locale) {

        if (bindingResult.hasErrors()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, String> errorFields = new HashMap<String, String>();
            for(FieldError fieldError : bindingResult.getFieldErrors()){
                errorFields.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return errorFields;
        }

        uiModel.asMap().clear();

        myService.create(personale);

    return null;
}

      

And it works, but it fieldError.getDefaultMessage()

returns an English message , but I need to return a Localized message ..

I know I can do this:

@NotNull(message="{myMessage}")
private Field field;

      

But I would not provide a localized message for each field, maybe I can use the message.properties

file ??

Is it possible?

Thank!

EDIT

I read this: another question about my problem , but I cannot get from messages ...

+3


source to share


1 answer


I faced the same problem and I could solve it like this:



  • Define your property messages in the src section (mybasename_locale.properties)
  • Include these elements in your config file (dispatcher-servlet.xml) to properly initialize your Spring l18n related classes

    <bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>mybasename</value>
    </property>
    
          

    <bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale">
        <value>es</value>
    </property>
    
          

  • In your controller, get a reference to your ResourceBundleMessageSource bean.

    @Autowired
    private ResourceBundleMessageSource mensajes;
    
          

  • Then you can get the error via the getMessage getMessage method (MessageSourceResolvable arg0, Locale arg1)

    @RequestMapping(path = "/login", method=RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Validacion> login(@Valid @RequestBody LoginUsuario login_usuario, BindingResult result) {
    
        if (result.hasErrors()) 
            {
                System.out.println("HAY ERRORES");
                System.out.println(mensajes.getMessage(result.getFieldError(), LocaleContextHolder.getLocale()));
            }
    
          

+2


source







All Articles