2013-02-04 41 views
6

我是Spring的新手,我遇到了問題。我有一個用於向控制器發送信息的表單。我並不需要或想要有一顆豆備份形式,所以我留在空白表單的commandName屬性是這樣的:不帶命令的彈簧形式

<form:form action="getReportFile.html" method="post"> 
      <table> 
       <tr> 
        <td><form:label path="field1">Field1:</form:label></td> 
       </tr> 
       <tr> 
        <td><form:select path="field1" items="${FieldMap}" />       
        </td> 
       </tr> 
       <tr> 
        <td><form:label path="field2">Field2:</form:label></td> 
       </tr> 
       <tr> 
        <td><form:input path="field2"/></td> 
       </tr> 
       <tr> 
        <td><input type="submit" value="Submit" /></td> 
       </tr> 
      </table> 
     </form:form> 

,我發現了以下錯誤:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute 

我可以看到here,當你不給commandName的值時,它使用默認的'command',但是,然後,我需要配置其他的東西嗎?我應該在dispatcher-servlet.xml中加入'command'豆嗎?那個豆怎麼樣?

我只是想要一個表單發送信息給控制器。 我真的必須創建一個bean來支持它嗎?

+0

嗯,其實問題是這個複製品,因爲這個之前問過:) @SotiriosDelimanolis –

回答

8

如果你根本不需要命令對象,那麼就避免使用Spring表單,並簡單地使用HTML表單。

所以,改變

<form:form action="getReportFile.html" method="post"> 
    . 
    . 
    . 
</form:form> 

<form action="getReportFile.html" method="post"> 
    . 
    . 
    . 
</form> 

Command對象確實不是強制性的。只有使用以下庫的<form:form></form:form>這樣的Spring形式纔是必需的。

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 

您可以選擇使用request.getParameter("paramName")方法,如果您使用HTML表單來接收請求參數。


if you don't have a form backing bean, you can't use the Spring tag since it does require one! Your "path" attribute on that tag is supposed to specify the path to the model bean's property for data binding.

http://forum.springsource.org/showthread.php?83532-how-to-have-form-without-command-object&p=279807#post279807

+0

謝謝!真的有幫助 –

+0

不客氣。如果您需要使用類似'HibernateValidator'的服務器端驗證,那麼您的回答中必須具有@jfrank所描述的支持bean。曾幾何時,我也需要避免支持bean(支持bean實際上不是必需的,因爲JSP頁面上的所有內容都只能由Spring JSON處理)。 – Lion

+1

這麼簡單,但顯然非常罕見。每個教程都使用form:form,這會帶來很多不經常被解釋的綁定包袱。我不認爲想要一個與模型無關的表單(例如搜索表單,聯繫表單)並不少見,但幾乎沒有教程能夠涵蓋它。 – mmcrae

3

我不知道是否可以在Spring MVC中創建一個沒有支持bean的表單,但是我認爲如果不使用bean,你不會得到太多的Spring MVC。那些你正在使用的form標籤(比如form:input)綁定到backing bean的屬性上,這可以讓你附加驗證,錯誤消息,類型轉換等等。你的意圖是簡單地將表單發佈到Spring控制器,並使用類似「request.getParameter('field1')」的代碼處理服務器上的所有表單域?然後我會建議只使用純HTML表單。

-1

只需添加CommandName的屬性,形成春季標籤。

<form:form method="post" action="save.web" commandName="person">