spring中的form标签中的modelAttribute和commandName属性之间的区别?

Pul*_*kit 91 forms spring-mvc modelattribute

在Spring 3中,我在jsp中的form标签中看到了两个不同的属性

<form:form method="post" modelAttribute="login">
Run Code Online (Sandbox Code Playgroud)

在此属性modelAttribute是表单对象的名称,其属性用于填充表单.我用它来发布一个表单,在控制器中,我习惯于@ModelAttribute捕获值,调用验证器,应用业务逻辑.这里一切都很好.现在

<form:form method="post" commandName="login">
Run Code Online (Sandbox Code Playgroud)

这个属性的期望是,它还是一个表单对象,我们将填充它们的属性?

Sot*_*lis 124

如果你查看支持你的元素FormTag(4.3.x)源代码<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;
}
Run Code Online (Sandbox Code Playgroud)

它们都指的是同一个领域,因此具有相同的效果.

但是,正如字段名称所示,modelAttribute应该是首选,正如其他人也指出的那样.

  • @Sangdol传统上,这个类叫做`<tag-name> Tag`.对于完全限定的类名,打开包含标记的库(`.jar`),在这种情况下为`spring-web`.在`META-INF`下,你会找到`spring-form.tld`.对于具有`org.springframework.web.servlet.tags.form.FormTag`的`<tag-class>`的`form`,它将有一个`<tag>`条目. (11认同)
  • 好的!你是如何找到与 from 标签相关的类的名称的? (2认同)

die*_*eke 17

OLD WAY = commandName

...
<spring:url value="/manage/add.do" var="action" />
    <form:form action="${action}" commandName="employee">
        <div>
            <table>
....
Run Code Online (Sandbox Code Playgroud)

NEW WAY = modelAttribute

..
<spring:url value="/manage/add.do" var="action" />
    <form:form action="${action}" modelAttribute="employee">
        <div>
            <table>
..
Run Code Online (Sandbox Code Playgroud)


jax*_*jax 13

前一段时间我有同样的问题,我不记得确切的差异,但从研究中我确定这commandName是旧方法,在新的应用程序中你应该使用modelAttribute