在控制器方法内以 post 模式重定向

Redirect in post mode inside a controller's method

编辑: 如果有人在遵循以下指南时遇到问题,我建议使用更简单的方法,例如:https://www.youtube.com/watch?v=yaxUV3Ib4vM


我仍在学习本教程:spring-mvc-radiobutton-and-radiobuttons-example 到目前为止我已经创建了这个控制器:

    @RequestMapping(value = "add", method = RequestMethod.GET)
public String add(Model model) {
    MyObject object = new MyObject();
    object.setParameter("fake parameter");
    model.addAttribute("add", object);
    initModelList(model);
    return "add";
}

@RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute("add") @Validated MyObject object, BindingResult result, Model model) {
    model.addAttribute("add", object);
    String returnVal = "redirect:/add/object";
    if(result.hasErrors()) {
        initModelList(model);
        returnVal = "add";
    } else {
        model.addAttribute("add", object);
    }       
    return returnVal;
}

@RequestMapping(value = "/add/object", method = RequestMethod.POST)
public String addObject(
                            @ModelAttribute MyObject object,
                            ModelMap model) throws DatatypeConfigurationException {
      try{
      ...marshalling results in xml output 
      ...inserting it in database
      ...showing the result

        return "objectResult";

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);

        throw new RuntimeException(e);
    }
}

当然这个解决方案是行不通的,因为重定向是 GET 类型的。 我尝试将最后两种方法融合在一起,如下所示:

    @RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute("add") @Validated MyObject object, BindingResult result, Model model)
         throws DatatypeConfigurationException {
    model.addAttribute("add", object);
    String returnVal = "objectResult";
    if(result.hasErrors()) {
        initModelList(model);
        returnVal = "add";
    } else {
        model.addAttribute("add", object);
    }       
    try{
    ...mashalling etcetera
        return returnVal;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);

        throw new RuntimeException(e);
    }
}

但是这样验证就不起作用了。我不知道如何解决这个问题,我想使用 spring 验证器,但如果我不能使用它,我将回归该项目,这是一种耻辱。

如果有人在遵循同一指南时遇到问题,我建议使用更简单的方法,例如:https://www.youtube.com/watch?v=yaxUV3Ib4vM 它不需要更新 Maven 依赖项