春天的表单标签中的modelAttribute和commandName属性之间的区别? [英] Difference between modelAttribute and commandName attributes in form tag in spring?
问题描述
在Spring 3中,我在jsp的form标记中看到了两个不同的属性
In Spring 3, I have seen two different attribute in form tag in jsp
<form:form method="post" modelAttribute="login">
在此属性modelAttribute是表单对象的名称,其属性用于填充表单.在发布表单时使用了它,在控制器中使用了@ModelAttribute
来获取值,调用验证器,应用业务逻辑.这里一切都很好.现在
in this the attribute modelAttribute is the name of the form object whose properties are used to populate the form. And I used it in posting a form and in controller I have used @ModelAttribute
to capture value, calling validator, applying business logic. Everything is fine here. Now
<form:form method="post" commandName="login">
此属性有什么用,它也是我们要填充其属性的表单对象吗?
What is expected by this attribute, is it also a form object whose properties we are going to populate?
推荐答案
If you look at the source code of FormTag
(4.3.x) which backs your <form>
element, you'll notice this
/**
* 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;
}
它们都指向相同的字段,因此具有相同的效果.
They are both referring to the same field, thus having same effect.
但是,正如字段名所示,modelAttribute
应该是首选,正如其他人也指出的那样.
But, as the field name indicates, modelAttribute
should be preferred, as others have also pointed out.
这篇关于春天的表单标签中的modelAttribute和commandName属性之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!