2

I have a form, but when I submit it, my initbinder doesn't intercept my post request. This is my initbinder:

@InitBinder(value="confermaDto")
    protected void initBinderDto(final WebDataBinder binder, final Locale locale) {
        binder.registerCustomEditor(MyClass.class, myClassEditor);
    }

And this is my method to intercept the post:

@RequestMapping(value="confermaDati", method = RequestMethod.POST)
public String confermaDati(@Valid final ConfermaDatiAttrezzaturaDto confermaDto,
        final BindingResult bindingResult, final Model uiModel, final HttpServletRequest httpServletRequest) {
    if (bindingResult.hasErrors()) {
        uiModel.addAttribute("message", "Errore Salvataggio");
        uiModel.addAttribute("dto", confermaDto);
    }
    uiModel.asMap().clear();
    return "redirect:/";
}

I think, that it should work because the value in initbinder, and the name of my model attribure are equal. So why don't it work??

Thank you

Teo
  • 3,143
  • 2
  • 29
  • 59

2 Answers2

3

If you do not specify a ModelAttribute value into RequestMapping annotated method You have to specify in value attribute of @Initbinder anotation the class required name with first letter NOT capitalized.

gipinani
  • 14,038
  • 12
  • 56
  • 85
3

The names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to.

Default is to apply to all command/form attributes and all request parameters processed by the annotated handler class. Specifying model attribute names or request parameter names here restricts the init-binder method to those specific attributes/parameters, with different init-binder methods typically applying to different groups of attributes or parameters.

Above is from the javadoc of @InitBinder.

In your code you specify the name of a model attribute to use, namely confermaDto. However in your request handling method there is no notion of a model attribute (i.e. nothing is annotated with @ModelAttribute).

public String confermaDati(@Valid final ConfermaDatiAttrezzaturaDto confermaDto, final BindingResult bindingResult, final Model uiModel, final HttpServletRequest httpServletRequest) { ... }

You have a argument annotated with @Valid which will only trigger validation, Spring will also instantiate this object and put values from the request onto it however it is NOT designated as a model attribute. Next to your @Valid annotation add the @ModelAttribute annotation. (Or remove the name from the @InitBinder annotation so that it will always be applied).

I think, that it should work because the value in initbinder, and the name of my model attribute are equal. So why don't it work??

In short to answer this question, the method argument name is equal but there is no model attribute. Hence no triggering of the @InitBinder method.

Community
  • 1
  • 1
M. Deinum
  • 115,695
  • 22
  • 220
  • 224