Spring MVC Controller, how to keep BindingResult errors, while emptying the form values

前端 未结 2 1836
感动是毒
感动是毒 2021-02-10 05:41

I have a web form, using Spring MVC Controller. The form is validated by Spring. When there are validation errors, Spring shows the same form, pre-filled in with the values ente

2条回答
  •  情歌与酒
    2021-02-10 06:31

    Edit : add another solution

    You can have an empty model object while keeping previous errors simply by copying fresh values (from a newly initialized object) into your model attribute via org.springframework.beans.BeanUtils:

    @RequestMapping(method = RequestMethod.POST)
    public String post(@Valid @ModelAttribute("myForm") MyForm myForm, Errors errors, Model model) {
        if (errors.hasErrors()) {
            MyForm emptyForm = new MyForm();
            BeanUtils.copyProperties(emptyForm, myForm);
            return "my_form";
        }
    
        return "redirect:/confirmation";
    }
    

    That way, you can still show previous errors, and the form is empty.

    There is still a caveat : if works fine when I use fields, but not with spring enhanced fields that do use the rejected value from errors.

    If you prefere to keep using fields, you will have to create another BindingResult object and initialize it with current errors, simply setting the rejected values to null. You have even the possibility to reset all fields or only the fields in error :

    @RequestMapping(value = "/form", method=RequestMethod.POST)
    public String update(@Valid @ModelAttribute Form form, BindingResult result, Model model) {
        if (result.hasErrors()) {
            // uncomment line below to reset all fields - by default only offending ones are
            //form = new Form();
            BeanPropertyBindingResult result2 = new BeanPropertyBindingResult(form, result.getObjectName());
            for(ObjectError error: result.getGlobalErrors()) {
                result2.addError(error);
            }
            for (FieldError error: result.getFieldErrors()) {
                result2.addError(new FieldError(error.getObjectName(), error.getField(), null, error.isBindingFailure(), error.getCodes(), error.getArguments(), error.getDefaultMessage()));
            }
            model.addAllAttributes(result2.getModel());
            return "my_form";
        }
    
        return "redirect:/confirmation";
    }
    

提交回复
热议问题