【发布时间】:2015-06-04 21:46:11
【问题描述】:
我是 Spring MVC 的新手。请帮我解压文档。
文档
Spring MVC Documentation 状态(强调我的):
@ModelAttribute在方法参数上表示应从模型中检索参数。如果模型中不存在,则应首先实例化参数,然后将其添加到模型中。一旦出现在模型中,参数的字段应该从具有匹配名称的所有请求参数中填充。 WebDataBinder 类匹配请求参数名称 — 包括查询字符串参数和表单字段 — 按名称对属性字段进行建模。@RequestParam将请求参数绑定到控制器中的方法参数。
免责声明/说明
我知道@ModelAttribute和@RequestParam不是同一个东西,不互斥,不扮演相同的角色,可以同时使用,就像this question一样——确实,@RequestParam可以用于填充@ModelAttribute 的字段。我的问题更针对他们内部运作之间的差异。
问题:
@ModelAttribute(用于方法参数,而不是方法)和@RequestParam 有什么区别?具体来说:
-
来源:
@RequestParam和@ModelAttribute是否具有相同的来源 信息/人口,即 URL 中的请求参数,可能已作为POSTed 的表单/模型的元素提供? -
用法:使用
@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类中的字段)。这些变量将在 Controller 完成后被丢弃,除非它们已被输入到模型中。@ModelAttribute填充类的字段,然后填充模型的属性以传回视图
这对吗?
【问题讨论】:
标签: java spring spring-mvc spring-annotations