簡體   English   中英

何時精確調用@ModelAttribute帶注釋的方法?

[英]When is a @ModelAttribute annotated method called precisely?

以下是一個簡單的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是否會保留單獨的模型副本?

所述setupItem將被稱為每次請求一次的任何@RequestMapping在該控制器的方法中,合適的前@RequestMapping被調用的方法。 因此,對於您的addItem方法,流程將是-調用setupItem ,創建一個名為item的模型屬性,因為您的addItem參數還被@ModelAttribute標記,此時將使用POST參數來增強該item

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM