2013-03-08 28 views
1

下面是我的代碼...@ModelAttribute不工作

@RequestMapping(value = "/submitnewstory", method = RequestMethod.POST) 
    @ResponseBody 
    public String save(@ModelAttribute("storyInsertForm") StoryInsertForm uploadForm, HttpSession session, Model map) { 
} 

HTML代碼:

<form:form id="contentForm" class="cssform2" action="submitnewstory" method="post" enctype="multipart/form-data" modelAttribute="storyInsertForm"> 

</form:form> 

發生了什麼事?

假設我的模型中有兩個字段(在這種情況下爲StoryInsertForm),即String firstnameString lastname。我必須在<form:form>內聲明相同的變量,像下面

<form:form id="contentForm" class="cssform2" action="submitnewstory" method="post" enctype="multipart/form-data" modelAttribute="storyInsertForm"> 
    <input type="text" name="firstname" id="firstname" /> 
    <input type="text" name="lastname" id="lastname" /> 
</form:form> 

正在發生的事情是,如果你給一個值的第一輸入,而忽略第二個數據甚至沒有達到控制器。但是,如果你提供所有的值,即爲兩個輸入類型的文本提供輸入,它會找到控制器,並且一切正常。

另一種看法說,如果你不申報的領域之一,即類似如下:

<form:form id="contentForm" class="cssform2" action="submitnewstory" method="post" enctype="multipart/form-data" modelAttribute="storyInsertForm"> 
    <input type="text" name="firstname" id="firstname" /> 
<!-- <input type="text" name="lastname" id="lastname" /> --> 
</form:form> 

仍然被貼在上面的字段中提供的數據(在這種情況下名字)的數據。

摘要

如果您有相關的你在輸入類型輸入一些值,否則沒有達到控制器在HTML中的字段。

期待您的幫助。

回答

0

我現在想什麼,

你也必須綁定表單輸入標籤使用

的Spring表單標籤庫。

<form:form id="contentForm" class="cssform2" action="submitnewstory" method="post" enctype="multipart/form-data" modelAttribute="storyInsertForm"> 
    <form:input path="firstname" id="firstname" /> 
    <form:input path="lastname" id="lastname" /> 
</form:form> 

此外,我不知道你的控制器編碼是什麼,所以我認爲以下幾點值得提及 -

1>在該頁面返回RequestMethod GET功能,爲表單添加模型屬性。

在這種情況下,全部編碼應該是 -

@RequestMapping(value = "/getpage.htm", method = RequestMethod.POST) 
public String getPage(Model model){ 
     ........ 
     Other Code Snippet 
     ......... 

    StoryInsertForm uploadForm = new StoryInsertForm(); 
    model.addAttribute(「storyInsertForm」, uploadForm); 
    return 「login」; 
} 

2>另外添加BindingResult參數數據保存方法,否則你應該得到一個異常 -

所以對於保存方法的代碼應該是 -

@RequestMapping(value = "/submitnewstory", method = RequestMethod.POST) 
    @ResponseBody 
    public String save(@ModelAttribute("storyInsertForm") StoryInsertForm uploadForm, BindingResult result, HttpSession session, Model map) { 
    ........... 
    Your Save Business Logic and Other DAO Method call etc... 
    ........... 
} 

我希望上面的代碼能夠解決您的問題。

0

我有同樣的問題;我解決不了,但可以通過使用

<form></form> 

規避它,而不是

<form:form></form:form> 

希望它能幫助!