4

Hi I have some Ajax Forms, where I use an Async POST to send data to server...

If BindingResult has an error I want show a message in 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 fieldError.getDefaultMessage() return an English message, but I want return a Localized message..

I know that I can do in this way:

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

But I wouldn't specify the localized message to each field, maybe can I use message.properties file??

Is it possible??

Thank you!

EDIT

I readed this: another question about my problem, but I can't get from messagges...

Community
  • 1
  • 1
Teo
  • 3,143
  • 2
  • 29
  • 59

1 Answers1

4

I faced the same problem and i could solve it on this way:

  1. Define your properties messages under src (mybasename_locale.properties)

  2. Include these elements on your config file (dispatcher-servlet.xml) in order to initialize properly the Spring's classes l18n related

    <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>
    
  3. In your controller, get a reference to your ResourceBundleMessageSource bean.

    @Autowired
    private ResourceBundleMessageSource messageSource;
    
  4. Then, you can get the error message through getMessage method getMessage(MessageSourceResolvable arg0, Locale arg1)

    @ResponseBody
    @PostMapping(path = "/login")        
    public ResponseEntity<?> login(@Valid @RequestBody User user, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println(messageSource.getMessage(result.getFieldError(), LocaleContextHolder.getLocale()));
        }
    
        // other stuff
    }
    
Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Val Martinez
  • 617
  • 6
  • 15