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

Kin*_*ere 1 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";
    }
Run Code Online (Sandbox Code Playgroud)

currentUser.getFirstname()打印出期望值,但是我在表单中得到空白的输入值。

谢谢。

Kin*_*ere 7

th:field通过完全删除并使用th:value存储默认值以及 htmlnameid模型字段来解决问题。所以name和 的id表现就像th:field


dar*_*rdo 5

我有点困惑,您要在模型图中添加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