【问题标题】:Difference between modelAttribute and commandName attributes in form tag in spring?spring中form标签中modelAttribute和commandName属性的区别?
【发布时间】:2014-02-25 01:34:09
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: forms spring-mvc modelattribute


    【解决方案1】:

    如果您查看支持您的&lt;form&gt; 元素的source code of FormTag (4.3.x),您会注意到这一点

    /**
     * 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 应该是首选,正如其他人也指出的那样。

    【讨论】:

    • 好!您是如何找到与 from 标签相关的类的名称的?
    • @Sangdol 按照惯例,该类仅称为&lt;tag-name&gt;Tag。对于完全限定的类名,打开包含标记的库 (.jar),在本例中为 spring-web。在META-INF 下,您会找到spring-form.tld。它将有一个&lt;tag&gt; 条目用于form,其中&lt;tag-class&gt;org.springframework.web.servlet.tags.form.FormTag
    【解决方案2】:

    OLD WAY = commandName

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

    新方法 = 模型属性

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        commandName = 请求范围或会话范围中包含有关此表单的信息的变量的名称,或者这是此视图的模型。 Tt 应该是。

        【讨论】:

          【解决方案5】:

          在基于 xml 的配置中,我们将使用命令类在控制器和视图之间传递一个对象。现在在注释中我们使用modelattribute

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-09-06
            • 2011-11-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-04-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多