Syntactically incorrect request sent upon submitting form with invalid data in Spring MVC (which uses hibernate Validator)

前端 未结 1 978
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-10 04:57

Login form:


    
相关标签:
1条回答
  • 2021-02-10 05:42

    You have to modify the order of your arguments. Put the BindingResult result parameter always directly after the parameter with the @Valid annotation.

    @RequestMapping(value = "login", method=RequestMethod.POST)
    public String submitloginForm(@Valid loginData logindata, BindingResult result,
                                  SessionStatus state, Model model)
    

    This was even mentioned in this weeks This Week in Spring - March 5th, 2013 blog entry

    Someone asked me this the other day and I felt like it was worthy of a mention: in your Spring MVC @Controller class handler methods, make sure that the BindingResult argument is immediately after the model or command argument, like this: @RequestMapping(...) public String handleRequest( @ModelAttribute @Valid YourCustomPojo attempt, BindingResult result). In this example, handleRequest will validate the POJO (YourCustomPojo) - checking the POJO for JSR303-annotations and attempting to apply the constraints because the POJO is annotated with @Valid - and stash any errors in the BindingResult, which it makes available if we ask for it.

    Spring will

    • 0) determin the handler method
    • 1) create an instance of loginData
    • 2) populate it
    • 3) validate it, and store the validation result in BindingResult
    • 4) invoke the method (with loginData and BindingResult values), no matter whenever the binding Result contains an error or not
    0 讨论(0)
提交回复
热议问题