Spring validation prior to submit (Method.GET)

2019-08-08 20:38发布

I'm experiencing a strange issue with Spring MVC (latest version, 4.0.6). While trying to validate a form before submitting it I'm able to get validation in place and populate given Spring Form's (truncated for sake of clarity)

<form:form method="post" commandName="contratto">
    <form:errors path="*" cssClass="alert alert-error" element="div" />
</form:form>

enter image description here

The problem is that Spring formatters are not called at all, therefore giving me unlocalized dates and numbers.

@RequestMapping(value = "/edit/{contractId}", method = RequestMethod.GET)
public String edit_form(@PathVariable("contractId") int id, ModelMap model) throws Exception {
    Contratti contratto = ejbRepository.getContratto(id);
    model.addAttribute("contratto", contratto);
    BindingResult result = new BeanPropertyBindingResult(contratto, "contratto");
    new CustomContrattoValidator().validate(contratto, result);
    if (result.hasErrors()) {
        model.addAllAttributes(result.getModel());
    }
return "contratti/form/edit";
}

By using classic approach, like annotating the handler method as stated in Display JSR-303 errors before form submission with Spring MVC or @Valid and Binding Result for Data from DB or Spring - adding BindingResult to newly created model attribute the issue is even worse, as the

new CustomContrattoValidator().validate(contratto, result);

seems to report all missing fields (like if the object is completely empty, even if the code is exactly the same and I'm getting it from DB).

I'm completely lost and can't get my head around.

Any advice is appreciated!

1条回答
唯我独甜
2楼-- · 2019-08-08 21:05

You need to set the conversion service in the BeanPropertyBindingResult.

Obtain the conversion service:

@Autowired private ConversionService conversionService;

Pass it along:

BindingResult result = new BeanPropertyBindingResult(contratto, "contratto");
result.initConversion(conversionService);
查看更多
登录 后发表回答