spring中formAttribute和commandName属性在form标签中的区别? [英] Difference between modelAttribute and commandName atributes in form tag in spring?
问题描述
我是Spring 3的新手,所以可能我正在问一个糟糕的标准问题。我在jsp中看到了两个不同的form标签属性:
< form:form method =postmodelAttribute =login >
在此属性中,modelAttribute是表单对象的名称,其属性用于填充表单。我用它发布表单并在控制器中使用 @ModelAttribute
来捕获值,调用验证器,应用业务逻辑。这里一切都很好。现在
< form:form method =postcommandName =login>
这个属性期望什么,它也是一个表单对象,它的属性我们将要填充? ?
如果您查看源代码 FormTag
(4.3.x),它支持你的< form>
元素,你会注意到这个
/ **
*在模型中设置表单属性的名称。
*< p>可能是一个运行时表达式。
* /
public void setModelAttribute(String modelAttribute){
this.modelAttribute = modelAttribute;
}
/ **
*获取模型中表单属性的名称。
* /
保护字符串getModelAttribute(){
返回this.modelAttribute;
}
/ **
*在模型中设置表单属性的名称。
*< p>可能是一个运行时表达式。
* @see #setModelAttribute
* /
public void setCommandName(String commandName){
this.modelAttribute = commandName;
}
/ **
*获取模型中表单属性的名称。
* @see #getModelAttribute
* /
protected String getCommandName(){
return this.modelAttribute;
}
它们都指向相同的字段,因此具有相同的效果。 p>
但是,正如字段名称所示, modelAttribute
应该是首选的,正如其他人也指出的那样。
I am new to Spring 3 so may be I am asking a poor standard question. I have seen two different attribute in form tag in jsp
<form:form method="post" modelAttribute="login">
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.
But, as the field name indicates, modelAttribute
should be preferred, as others have also pointed out.
这篇关于spring中formAttribute和commandName属性在form标签中的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!