我已经看到了许多有关simpleFormcontroller如何工作的示例。

但是我仍然有些困惑。

我想知道何时调用formBackingObject()referenceData()onSubmit()方法吗?

我不知道这些方法的确切工作流程?

谁能解释我?

最佳答案

从Spring 3.0开始不推荐使用SimpleFormController
在Spring 3.0中,将一个 Controller 与两种方法一起用于创建过程(第三种方法用于显示页面)。它通常看起来像这样:

/**
 * Shows a form for car creation.
 */
@RequestMapping(params = "form", method = RequestMethod.GET)
public ModelAndView createForm() {
    ModelMap uiModel = new ModelMap();
    uiModel.addAttribute("carCreateFormBackingObject", new CarCreateFormBackingObject()); //formBackingObject - often called command object
    uiModel.addAttribute("manufactureres", this.manufactureresDao.readAll()); //referenceData
    return new ModelAndView("car/create", uiModel);
}

/**
 * Creates the car and redirects to its detail page.
 *
 */
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(final @Valid CarCreateFormBackingObject carCreateFormBackingObject,
        final BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
                ModelMap uiModel = new ModelMap();
        uiModel.addAttribute("carCreateFormBackingObject", carCreateFormBackingObject);
        uiModel.addAttribute("manufactureres", this.manufactureresDao.readAll()); //referenceData
        return new ModelAndView("car/create", uiModel);
    }

    Car car = this.carService.create(carCreateFormBackingObject.name, ...);
    return new ModelAndView(new RedirectView("/cars/" + car.getId(), true)); //redirect to show page
}

我还是想知道formBackingObject(),refernceData()方法由谁以及何时自动调用?

回到您的问题“我仍然想知道formBackingObject(),refernceData()方法由谁以及何时自动调用?”

所有这些方法均由SimpleFormController(及其父类(super class)AbstractFormController)调用,然后遵循Template-Method-Pattern。 -SimpleFormController定义了该过程,并在该过程的某些挂钩中定义了具体的子类“plugsin”以获取业务值(value)。

当 Controller 需要处理Submit(POST)或为初始"new" View 构建Command对象时,由formBackingObject调用
  • AbstractFormController
  • referenceData在需要为 View 构建模型时始终被调用AbstractFormController
  • 07-26 04:49