Spring MVC 验证表单和 return 数据(如果有错误)

Spring MVC Validate form and return data if has errors

我可以成功验证我的表单甚至 return 错误。 当我的视图有一些选择需要用来自控制器的数据填充时,我的问题就开始了。

当我执行 model.addAttribute(...) 时,它停止将错误传递给视图:

 public String registerSubmit(@Valid @ModelAttribute("jconcorrente") Jconcorrentes concorrente, BindingResult result, HttpServletRequest request, Model model){

         if(result.hasErrors()) {
             model.addAttribute("listJdistrito", this.jdistritoService.listJdistrito());
             model.addAttribute("listJtipocodiden", this.jtipodocidenService.listJtipodociden());
             model.addAttribute("jconcorrente", new Jconcorrentes());
                return "register";
            }

所以我的问题是如何在不影响验证错误的情况下传递数据?

我猜你的错误没有被填充,因为你将模型属性的新实例直接添加到模型中。

尝试删除这一行:

model.addAttribute("jconcorrente", new Jconcorrentes());

从您的 if 语句创建新方法,如下所示:

@ModelAttribute("jconcorrente")
public Jconcorrentes getJconcorrentes() {
    return new Jconcorrentes();
}

保持其他一切不变,它应该可以工作。