首页 > 解决方案 > Spring、Java、HTML:如何使用值填充 HTML 表单?

问题描述

我想写一个网站的一部分,让用户更改现有书籍的数据。为此,我正在尝试使用一种可以正常工作的表格。我只是不知道如何让表单在编辑字段中显示数据,这样用户就不必再次输入所有内容,而只需更改一些细节。我的 HTML 代码如下所示:

<form method="post" role="form" class="ui form" id="bookForm" th:action="@{/editBook}" th:object="${bookForm}">
    <div class="field">
        <label for="name">Book</label>
        <input id="name" name="name" th:field="*{name}" th:errorclass="fieldError" type="text" required="required"/><br/>
    </div>

我包含了更多关于错误和其他内容的代码,但这基本上是我希望表单不仅将值传递给我的 java 文件,而且还获取有关书籍的值并将它们显示在编辑字段中。我想我需要将用户想要编辑的书传递到此表单中,但我不确定如何。我努力了:

<input type="hidden" id="currentBook" name="currentBook" th:value="${currentBook}"/>

就在“div”语句之前,然后将“currentBook”传递给 HTML

model.addAttribute("currentBook", currentBook); 

在该网站的我的@GetMapping 方法中。然后,我也将字段中的“输入”语句更改为

<input id="name" name="name" th:field="*{name}" th:value="${currentBook.name}" th:errorclass="fieldError" type="text" required="required"/><br/>

currentBook.name 会给我那本书的名字,只是不在这个上下文中。有谁知道我做错了什么以及它将如何工作?

先感谢您!

标签: javahtmlspringforms

解决方案


推荐阅读