如何在Thymeleaf的输入字段中添加默认值

时间:2015-07-21 14:33:01

标签: html html5 spring spring-mvc thymeleaf

我在Spring编程并使用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()打印出预期值,但我在表单中输入空白值。

感谢。

3 个答案:

答案 0 :(得分:4)

我有点困惑,你正在将currentUser和一个新的用户对象添加到模型地图中。

但是,如果currentUser是目标对象,那么您只需:

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

从文档中: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

答案 1 :(得分:3)

通过完全删除th:field并使用th:value存储默认值,并使用html nameid作为模型字段来解决问题。因此nameid的行为与th:field相似。

答案 2 :(得分: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>

在另一篇帖子中,用户推荐使用&#34; th:attr&#34;属性,但它也没有工作。

这终于奏效 - 我只是添加了name元素(&#34; id&#34;是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> 
相关问题