【问题标题】:When is a @ModelAttribute annotated method called precisely?何时精确调用 @ModelAttribute 注释方法?
【发布时间】:2012-07-14 16:32:07
【问题描述】:

以下是一个简单的 Spring 表单控制器,用于处理“添加项目”用户请求:

@Controller
@RequestMapping("/addItem.htm")
public class AddItemFormController {

    @Autowired
    ItemService itemService;

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(ModelMap model) {
        return "addItem";
    }

    @ModelAttribute("item")
    public Item setupItem() {
        Item item = new Item();
        return item;
    }

    @RequestMapping(method = RequestMethod.POST)
    protected String addItem(@ModelAttribute("item") Item item) {
        itemService.addItem(item);
        return "itemAdded";
    }

}

我在某处读到:(...) the @ModelAttribute is also pulling double duty by populating the model with a new instance of Item before the form is displayed and then pulling the Item from the model so that it can be given to addItem() for processing.

我的问题是,setupItem() 的准确调用时间和频率是多少?如果用户请求多个添加项,Spring 会保留单独的模型副本吗?

【问题讨论】:

    标签: java spring data-binding spring-mvc modelattribute


    【解决方案1】:

    setupItem 将在此控制器中的任何@RequestMapping 方法的每个请求中调用一次,就在调用@RequestMapping 方法之前。因此,对于您的addItem 方法,流程将是-调用setupItem,创建一个名为item 的模型属性,因为您的addItem 参数也被标记为@ModelAttributeitem 将得到增强此时使用 POST 参数。

    【讨论】:

    • 好的,所以对于 setupForm(),创建一个项目并将其存储在模型中,以便稍后在 addItem.jsp 中显示,对于 addItem(),还创建一个项目,并“填充”返回值由用户,对吗?
    猜你喜欢
    • 2018-01-10
    • 2017-08-03
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多