我在理解表单如何在Spring 3 MVC工作中提交时遇到问题。表单在Spring MVC 3中提交 - 解释
我想要做的是创建一个控制器,该控制器会将用户的姓名显示给他。不知何故,我已经做到了,但我并不真正了解它是如何工作的。所以..
我有一个表格,看起来像这样:
<form:form method="post" modelAttribute="person">
<form:label path="firstName">First name</form:label>
<form:input path="firstName" />
<br />
<form:label path="lastName">Last name</form:label>
<form:input path="lastName" />
<br />
<input type="submit" value="Submit" />
</form:form>
我也有一个控制器,它看起来像这样:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHelloPage(Model model) {
model.addAttribute("person", new Person());
return "home";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String sayHello(Person person, Model model) {
model.addAttribute("person", person);
return "home";
}
}
要显示一个值得欢迎的消息,我用一个用户在JSP页面下面的代码:
<c:if test="${not empty person.firstName and not empty person.lastName}">
Hello ${person.firstName} ${person.lastName}!
</c:if>
和它的作品(我省略了XML配置文件,因为它们AR与问题无关)。
我认为表单中的“modelAttribute”属性指向应该用输入值填充的bean变量(如在其“路径”属性中设置)。但看起来,它的工作方式非常不同。如果我删除线
model.addAttribute("person", new Person());
from“showHelloPage”method我得到一个(共同)异常“既不BindingResult也不...”。
此外,在开始时, “的sayHello” 方法看起来像:
(...)
public String sayHello(@ModelAttribute("person") Person person, Model model) {
(...)
我的意思是,它有 “的ModelAttribute” 的注释。我添加了它,因为在我读过的教程中,它始终存在。但是在我删除它之后,一切运行良好,就像以前一样。
所以我的问题是 - “ModelAttribute”anonnatation的用法是什么?是否有某种方式可以省略表单中的“modelAttribute”属性?第二部分,创建表单的方式(可能是某些注释)会自动将输入的值绑定到适当的bean的属性(将被声明为方法参数)?在发送表单之前不需要添加空的bean(因为我现在必须这样做)。
感谢您的回复(因为我已经阅读过它,所以不是Spring文档的链接)。
非常感谢您的回复,您向我解释了很多。还有一个关于“ModelAttribute”注释的问题 - 如果我理解正确,这个注释与方法参数一起使用,相当于“model.addAttribute(...)”? –
@MichałTabor尝试将其添加为方法参数。我不确定,如果因为请求没有任何可以绑定的请求参数,它会返回'null'。否则,你正在做的方式是正确的。这些被称为数据传输对象(或Spring表单支持对象/命令对象)。文档应该有更多的细节。 –
+1,很好的解释 – rocketboy