我是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
填充一个类的字段,然后填充模型的属性将被传递回视图
这是正确的吗?