在Spring 3中,我在jsp的form标记中看到了两个不同的属性
<form:form method="post" modelAttribute="login">
在这种情况下,属性modelAttribute是表单对象的名称,其属性用于填充表单。我用它来发布表单,并在控制器中用来@ModelAttribute捕获价值,调用验证器,应用业务逻辑。这里一切都很好。现在
@ModelAttribute
<form:form method="post" commandName="login">
此属性有什么用,它也是我们要填充其属性的表单对象吗?
如果您查看支持元素的FormTag(4.3.x)源代码<form>,则会注意到这一点
FormTag
<form>
/** * Set the name of the form attribute in the model. * <p>May be a runtime expression. */ public void setModelAttribute(String modelAttribute) { this.modelAttribute = modelAttribute; } /** * Get the name of the form attribute in the model. */ protected String getModelAttribute() { return this.modelAttribute; } /** * Set the name of the form attribute in the model. * <p>May be a runtime expression. * @see #setModelAttribute */ public void setCommandName(String commandName) { this.modelAttribute = commandName; } /** * Get the name of the form attribute in the model. * @see #getModelAttribute */ protected String getCommandName() { return this.modelAttribute; }
它们都指的是同一领域,因此具有相同的作用。
但是,正如字段名所指示的那样,modelAttribute应该首选,正如其他人也指出的那样。
modelAttribute