SpringMVC controller: how to stay on page if form validation error occurs

前端 未结 3 1840
野性不改
野性不改 2020-12-30 15:45

I have next working code in my SpringMVC controller:

@RequestMapping(value = \"/register\", method = RequestMethod.GET)
public void registerForm(Mod         


        
3条回答
  •  再見小時候
    2020-12-30 16:24

    You can change your POST implementation to this:

    @RequestMapping(value = "/buy/{buyId}", method = RequestMethod.POST)
    public String buyPost(@PathVariable long buyId,
                              @Valid @ModelAttribute("buyForm") BuyForm buyForm,
                              BindingResult result) {
    
        buyForm.setId(buyId); // important to do this also in the error case, otherwise, 
                              // if the validation fails multiple times it will not work.
    
        if (result.hasErrors()) {
            byForm.setId(buyId);
            return "/buy/{buyId}";
        }
    
        buyService.buy(buyForm);
        return "redirect:/show/{buyId}";
    }
    

    Optionally, you can also annotate the method with @PostMapping("/buy/{buyId}") if you use Spring 4.3 or higher.

提交回复
热议问题