Post 表格在 th:each 部分 [Spring-Boot + Thymeleaf]

Post form in a th:each section [Spring-Boot + Thymeleaf]

我正在显示一个对象列表,我想为每个对象显示一个按钮以访问所选对象的特定配置文件页面。我尝试使用隐藏输入并将所选对象的 ID 传递给它,但在控制器中 ID 为空。

这是 html 页面中的代码。

<table class="table table-secondary table-bordered">
                    <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Nome Laboratorio</th>
                        <th scope="col">Indirizzo Laboratorio</th>
                        <th scope="col">Distanza dal Laboratorio</th>
                        <th scope="col">Dettagli</th>
                    </tr>
                    </thead>

                    <tbody>
                    <tr th:each="element,iterationStatus : ${lista}">
                        <td th:text="${iterationStatus.count}" style="width: 10px"></td>
                        <td th:text="${element.laboratorio.nome}"></td>
                        <td th:text="${element.laboratorio.indirizzo}"></td>
                        <td th:text="${#numbers.formatDecimal(element.distanza,1,2,'POINT')} +' km'"></td>
                        <td>
                            <form th:action="@{/cittadino/selected}" th:object="${laboratorio}" th:method="post">
                                <input class="form-control" type="hidden"
                                       th:attr="value=${element.laboratorio.id}" th:field="*{id}"/>
                                <button type="submit">Visualizza</button>
                            </form>
                        </td>
                    </tr>
                    </tbody>
                </table>

这是控制器中的 post-映射。

@PostMapping("selected")
    public String laboratorioSelezionato(@ModelAttribute("laboratorio") Laboratorio laboratorio,
                                         Model model) {
        // System.out.println(laboratorio.getId());
        Laboratorio lab1 = laboratorioRepository.getById(laboratorio.getId());
        model.addAttribute("laboratorio",lab1);
        return "laboratorio/indexForUtente";
    }

控制器中的字段id为空。我可以尝试什么?

使用带有路径变量的 GetMapping 会更容易。

将您的 HTML 更改为:

...
<td>
 <a th:href="@{/cittadino/{id}(id=${laboratorio.id})}" th:text="#{select.item}"></a>
</td

在你的控制器中:

@GetMapping("/{id}")
public String laboratorioSelezionato(@PathVariable("id") String id, Model model) {
Laboratorio lab1 = laboratorioRepository.getById(id);
        model.addAttribute("laboratorio",lab1);
        return "laboratorio/indexForUtente";
}

我在这里使用 String 作为 id 的类型,但如果您使用 longUUID,请根据需要调整类型。