I have an ArticleFormModel containing data submitted by a normal html form that is entered by Spring using the @ModelAttribute annotation, i.e.
@RequestMapping(value="edit", method=RequestMethod.POST) public ModelAndView acceptEdit(@ModelAttribute ArticleFormModel model, HttpServletRequest request, BindingResult errors) {
Everything works fine to some degree. The problem is that ArticleFormModel contains a double field ( protected , set using a regular setter). Everything works fine as long as the data sent by the user is a number. When they type a word, all I get is a 400 Bad Request Http Error .
I already registered WebDataBinder for this controller
@InitBinder protected void initBinder(WebDataBinder binder) throws ServletException { binder.setValidator(validator); }
where validator is an instance of a custom class that implements the org.springframework.validation.Validator interface but I donβt know what to do next. I would like to be able to parse the model, get a valid HTTP response, and display an error message in the form. The initBinder() method is initBinder() and I can call validator.validate() , but it does not change the error (for this incorrect data).
I know that I could use setter to parse a string, check if this number is, if not, store this information in a variable, and then retrieve this variable during validation, but this seems to work too much. There should be an easier way to force the type on the field without getting an error. In addition, the problem is with data binding, not validation, so I believe that it should be placed in the appropriate code layer.
I also thought about implementing java.beans.PropertyEditor and calling binder.registerCustomEditor() , but I lack a reliable source of knowledge.
Checking on the client side (checking if the number of data using JavaScript) is not possible.
TL DR:
How can I make a field be of a specific type for an @ModelAttribute element without receiving a 400 Bad Request Http Error ?