2015-07-21 152 views
0

我在Spring中編程,並使用Thymeleaf作爲我的視圖,並試圖創建一個用戶可以更新其配置文件的表單。我有一個配置文件頁面,列出用戶的信息(名字,姓氏,地址等),並有一個鏈接,指出「編輯配置文件」。當點擊該鏈接時,它會將它們帶到可以編輯其個人資料的表單中。表單由可輸入的文本字段組成,就像您的標準註冊表單一樣。如何將默認值添加到Thymeleaf中的輸入字段

一切工作正常,但我的問題是,單擊該鏈接時,如何將用戶的信息添加到輸入字段,以便它已經存在,並且他們只修改他們想要更改而不是重新進入所有的領域。

這應該表現得像一個標準的「編輯配置文件」頁面。

這是我edit_profile.html頁面的部分:

名字:

這裏是返回edit_profile.html頁面視圖控制器方法:

@RequestMapping(value = "/edit", method = RequestMethod.GET) 
    public String getEditProfilePage(Model model) { 
     model.addAttribute("currentUser", currentUser); 
     System.out.println("current user firstname: " + currentUser.getFirstname()); 
     model.addAttribute("user", new User()); 
     return "edit_profile"; 
    } 

currentUser.getFirstname( )打印出預期值,但是我在表單中獲得空白輸入值。

謝謝。

回答

2

通過完全消除th:field,而是使用th:value來解決問題存儲默認值,併爲模型字段存儲html nameid。因此nameid的行爲如同th:field

3

我有點困惑,你將currentUser和new'd用戶對象添加到模型映射中。

但是,如果currentUser是目標對象,你只是做:

<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />

從文檔: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

+0

不,我想顯示對象「currentUser」的當前信息。輸入新字段後,它們將存儲在「用戶」中,並且「用戶」對象將作爲PUT請求發送以更新字段。 – Kingamere

+0

然後你試圖將兩個不同的狀態綁定到一個字段,只有這樣,我才能看到正在完成的是通過一些JavaScript欺騙。 – dardo

1

我沒有一個帶有輸入元素的表單,但只有一個按鈕應該調用特定的Spring Controller方法,並在列表中提交一個動物的ID(所以我有一個已經在我的頁面上顯示的anmials列表)。我努力了一些時間來弄清楚如何在表單中提交這個id。這是我的解決方案:

因此,我開始有一個只有一個輸入字段的窗體(我將在最後更改爲隱藏字段)。在這種情況下,提交表單後,id將是空的。

<form action="#" th:action="@{/greeting}" th:object="${animal}" method="post"> 
    <p>Id: <input type="text" th:field="*{id}" /></p> 
    <p><input type="submit" value="Submit" /> </p> 
</form> 

下面沒有提示錯誤,但是也沒有提交animalIAlreadyShownOnPage的ID。

<form action="#" th:action="@{/greeting}" th:object="${animal}" method="post"> 
    <p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p> 
    <p><input type="submit" value="Submit" /> </p> 
</form> 

在另一篇文章中,用戶推薦了「th:attr」屬性,但它也不起作用。

這終於奏效了 - 我只是添加了名稱元素(「id」是Animal POJO中的一個String屬性)。

<form action="#" th:action="@{/greeting}" th:object="${animal}" method="post"> 
    <p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>        
    <p><input type="submit" value="Submit" /> </p> 
</form> 
+0

對於其他焦點的區別是添加了屬性名稱 – Babu

相關問題