java - 如何使用 Thymeleaf 将元素添加到集合中

标签 java html spring thymeleaf

在我的 Spring/Thymeleaf/Hibernate 项目中,我需要能够将元素添加到编辑对象的字段(即 List<>)。既然不允许嵌入,我该如何做到这一点? 类似这样的事情:

@Entity
public class Recipe {
    @Id
    private int id;

    private String name;
    private String description;
    private List<String> steps;
}

还有我的 thymeleaf 模板:

<form th:action="@{|/save/${recipe.id}|}" method="post" th:object="${recipe}">

<input type="hidden" th:field="${recipe.id}" th:value="${recipe.id}"/>
<input type="text" th:field="${recipe.name}" th:value="${recipe.name}"/>
<input type="text" th:field="${recipe.description}" th:value="${recipe.description}"/>

<input th:each="step : ${recipe.steps}" type="text" th:field="${step}" th:value="${step}"/>

<!-- And here I want make ability add new step element to List<String> steps -->

如何制作,而不丢失已经编辑的Recipe对象的数据? 添加使用 <form><button type="submit"> ? 或者只是使用 <a href> ?那么如何不丢失输入的数据呢?

最佳答案

嗯,找到了解决方案,当然不理想,但它有效。 在我的类中添加了字段(它将是标志,我们应该在 form-action-url 的端点中做什么:将步骤添加到列表并重定向以再次编辑或只是保存。并且表单有 2 个提交按钮: 和 ,通过 JavaScrypt 将标志字段更改为“步骤”,所以我会知道我已将元素添加到列表并重定向回来。 JavaScrypt:

<script type="text/javascript">
    function toggleAddedStep()
    {
        document.getElementById("recipeAddedFlag").value = "step";
    }
    function toggleAddedNothing()
    {
        document.getElementById("recipeAddedFlag").value = "";
    }
</script>

关于java - 如何使用 Thymeleaf 将元素添加到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39179828/

相关文章:

java - 在 Controller 类中使用自定义注释时 Autowiring 不起作用

java - eclipse 中 Ctrl-f6 的对话框名称

java - 如何获取图像渲染大小?

javascript - 访问html元素值javascript

javascript - 使用 javascript 定位表格内的所有标签

java - 事务看似回滚,但数据库中并没有回滚

java - 使用(平面)映射优于简单的空检查的优点?

java - 无法从不同 jar 中的同一包访问父类(super class)的 protected 成员

javascript - HTML 输入类型图像不会在单击时重定向?

java - 找不到类 org.apache.commons.dbcp.BasicDataSource