简体   繁体   English

何时精确调用@ModelAttribute带注释的方法?

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

The following is a simple Spring form controller to handle 'add item' user requests: 以下是一个简单的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";
    }

}

I read somewhere that: (...) 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. 我在某处读到: (...) 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.

My question is, when and how often is setupItem() going to be called precisely? 我的问题是, setupItem()何时以及多久被精确调用一次? Will Spring keep a separate model copy if user requests multiple add item? 如果用户请求多个添加项,Spring是否会保留单独的模型副本?

The setupItem is going to be called once per request to any of the @RequestMapping methods in this controller, right before the @RequestMapping method is called. 所述setupItem将被称为每次请求一次的任何@RequestMapping在该控制器的方法中,合适的前@RequestMapping被调用的方法。 So for your addItem method the flow will be - call the setupItem , creating a model attribute called item , since your addItem argument is also tagged with @ModelAttribute , the item is going to be enhanced with POST'ed parameters at this point. 因此,对于您的addItem方法,流程将是-调用setupItem ,创建一个名为item的模型属性,因为您的addItem参数还被@ModelAttribute标记,此时将使用POST参数来增强该item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM