Model Attribute 和 commandName 属性在春季表单标签中的区别?

在 Spring3中,我在 jsp 的表单标记中看到了两个不同的属性

<form:form method="post" modelAttribute="login">

其中属性 model Attribute 是用于填充表单的表单对象的名称。我在发布表单时使用它,在控制器中使用 @ModelAttribute捕获值,调用验证器,应用业务逻辑。这里一切都很好。现在

<form:form method="post" commandName="login">

这个属性的期望是什么,它是否也是一个我们要填充其属性的表单对象?

86100 次浏览

I had the same question a while ago, I can't remember the exact differences but from research I ascertained that commandName was the old way of doing it and in new applications you should be using modelAttribute

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.

OLD WAY = commandName

...
<spring:url value="/manage/add.do" var="action" />
<form:form action="${action}" commandName="employee">
<div>
<table>
....

NEW WAY = modelAttribute

..
<spring:url value="/manage/add.do" var="action" />
<form:form action="${action}" modelAttribute="employee">
<div>
<table>
..

In xml based config, we will use command class to pass an object between controller and views. Now in annotation we are using modelattribute.

commandName = name of a variable in the request scope or session scope that contains the information about this form,or this is model for this view. Tt should be a been.