我是Spring MVC的新手。請幫我解開文檔。Spring MVC:請解釋@RequestParam和@ModelAttribute之間的區別
文檔
Spring MVC Documentation狀態(重點煤礦):
@ModelAttribute
上的方法參數指示參數應該從模型中檢索。如果模型中不存在,則應首先實例化參數,然後將其添加到模型中。一旦出現在模型中,參數的字段應該從具有匹配名稱的所有請求參數填充。 WebDataBinder類將請求參數名稱(包括查詢字符串參數和表單字段)與名稱建模屬性字段相匹配。@RequestParam
將請求參數綁定到控制器中的方法參數。
免責聲明/澄清
我知道@ModelAttribute
和@RequestParam
是不一樣的東西,並不是相互排斥的,不執行相同的作用,並能同時使用,如this question - 的確,@RequestParam
可以用於填充@ModelAttribute
的字段。我的問題更多地針對他們內部工作之間的差異。
問:
是什麼@ModelAttribute
之間的差異,@RequestParam
(在方法的參數,而不是方法使用)?具體做法是:
- 來源:待辦事項
@RequestParam
和@ModelAttribute
具有 信息/人口,在URL即請求參數相同的源,其可以被供給作爲一種形式/模型,這是POST
版的要素是什麼? - 用法:用
@RequestParam
檢索到的變量是否被丟棄(除非傳入模型中),而使用@ModelAttribute
檢索的變量是否被自動送入要返回的模型?
或者在非常基本的編碼示例中,這兩個示例之間的真實工作區別是什麼?
實施例1:@RequestParam
:
// foo and bar are thrown away, and are just used (e.g.) to control flow?
@RequestMapping(method = RequestMethod.POST)
public String testFooBar(@RequestParam("foo") String foo,
@RequestParam("bar") String bar, ModelMap model) {
try {
doStuff(foo, bar);
}
// other code
}
實施例2:@ModelAttribute
:
// FOOBAR CLASS
// Fields could of course be explicitly populated from parameters by @RequestParam
public class FooBar{
private String foo;
private String bar;
// plus set() and get() methods
}
// CONTROLLER
// Foo and Bar become part of the model to be returned for the next view?
@RequestMapping(method = RequestMethod.POST)
public String setupForm(@ModelAttribute("fooBar") FooBar foobar) {
String foo = fooBar.getFoo();
String bar = fooBar.getBar();
try {
doStuff(foo, bar);
}
// other code
}
我的當前理解:
@ModelAttribute
和@RequestParam
博個詢問請求參數的信息,但他們不同的方式使用這些信息:
@RequestParam
只是填充獨立變量(當然這可能是一個@ModelAttribute
類字段)。這些變量在控制器完成時將被丟棄,除非它們已被饋入模型中。@ModelAttribute
填充一個類的字段,然後填充模型的屬性將被傳遞迴視圖
這是正確的嗎?