SpringMVC控制器:如果发生表单验证错误,如何留在页面上


问题内容

我的 SpringMVC 控制器中有下一个工作代码:

@RequestMapping(value = "/register", method = RequestMethod.GET)
public void registerForm(Model model) {
    model.addAttribute("registerInfo", new UserRegistrationForm());
}

@RequestMapping(value = "/reg", method = RequestMethod.POST)
public String create(
        @Valid @ModelAttribute("registerInfo") UserRegistrationForm userRegistrationForm,
        BindingResult result) {

    if (result.hasErrors()) {
        return "register";
    }
    userService.addUser(userRegistrationForm);
    return "redirect:/";
}

简而言之,create尝试验证UserRegistrationForm。如果表单有错误,它将使用户在同一页面上填写表单字段,并在其中显示错误消息。

现在,我需要将相同的行为应用于另一个页面,但是在这里我遇到了一个问题:

@RequestMapping(value = "/buy/{buyId}", method = RequestMethod.GET)
public String buyGet(HttpServletRequest request, Model model, @PathVariable long buyId) {
    model.addAttribute("buyForm", new BuyForm());
    return "/buy";
}

@RequestMapping(value = "/buy/{buyId}", method = RequestMethod.POST)
public String buyPost(@PathVariable long buyId,
                          @Valid @ModelAttribute("buyForm") BuyForm buyForm,
                          BindingResult result) {

    if (result.hasErrors()) {
        return "/buy/" + buyId;
    }

    buyForm.setId(buyId);
    buyService.buy(buyForm);
    return "redirect:/show/" + buyId;
}

我遇到了动态网址的问题。现在,如果表单有错误,我应该指定相同的页面模板以保留在当前页面上,而且还应该将其buyId作为路径变量传递。这两个要求在哪里冲突。如果我按原样保留此代码,则会收到错误消息(我将
Thymeleaf 用作模板处理器):

Error resolving template "/buy/3", template might not exist or might not be accessible by any of the configured Template Resolvers

我可以写类似的东西return "redirect:/buy/" + buyId,但是在这种情况下,我会丢失所有数据和form对象的错误。

我应该怎么做才能在buyPost方法中实现与方法相同的行为create


问题答案:

我想在这个文件档案化管理解决方案后,在本周末,但它并不适用于BindingResult工作。

下面的代码有效,但并不完美。

@ModelAttribute("command")
public PlaceOrderCommand command() {
    return new PlaceOrderCommand();
}

@RequestMapping(value = "/placeOrder", method = RequestMethod.GET)
public String placeOrder(
        @ModelAttribute("command") PlaceOrderCommand command,
        ModelMap modelMap) {
    modelMap.put(BindingResult.MODEL_KEY_PREFIX + "command",
            modelMap.get("errors"));
    return "placeOrder";
}

@RequestMapping(value = "/placeOrder", method = RequestMethod.POST)
public String placeOrder(
        @Valid @ModelAttribute("command") PlaceOrderCommand command,
        final BindingResult bindingResult, Model model,
        final RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        redirectAttributes.addFlashAttribute("errors", bindingResult);

        //it doesn't work when passing this          
        //redirectAttributes.addFlashAttribute(BindingResult.MODEL_KEY_PREFIX + "command", bindingResult);

        redirectAttributes.addFlashAttribute("command", command);
        return "redirect:/booking/placeOrder";
    }
    ......
}