java - 使用 thymeleaf 在 spring mvc 应用程序中从数据库生成 html 选择选项

标签 java spring hibernate spring-mvc thymeleaf

在使用 hibernate 的基于 spring 的 Web 应用程序中,我有一个lists.html 文件,其中在许多 View 中重用选择选项代码,现在选项将被传输到数据库,我的任务是从数据库填充这些列表。此代码很少更新。这是列表及其用法的示例。
lists.html

 <select th:fragment="typeList">
        <option selected value=""></option>
        <option th:value="|1|" th:text="|Type #1|"></option>
        <option th:value="|2|" th:text="|Type #2|"></option>
        <option th:value="|3|" th:text="|Type #3|"></option>
        <option th:value="|4|" th:text="|Type #4|"></option>
 </select>

使用

<li>
      <label for="type" th:text="#{type.label}">type</label>
      <select th:field="*{type}" th:include="html/fragments/lists :: typeList"></select>
</li>

从数据库字典构建这个lists.html的最佳方法是什么?

最佳答案

我的 DTO

@Entity
@Table(name = "TableName")
public class Test {

    @Id
    private String Code;
    private String Name;
    private int price;

    public Test() {}

    public Test(String Code, String Name, int price) {
        this.Code = Code;
        this.Name = Name;
        this.price = price;
    }

    public String getCode() {
        return Code;
    }

    public String getName() {
        return Name;
    }

    public int getPrice() {
        return price;
    }
}

查看

List<Test> test = new ArrayList<>();
    model.addAttribute("test", test);
    List<Test> tests = testRepository.findAll();
    model.addAttribute("tests", tests);

HTML

    <select class="form-control" id="Order" name="Order">
        <option value="">Select Test Order</option>
        <option th:each="test : ${tests}"
                th:value="${test.Code}"
                th:text="${test.Code}+' : '+${test.Name}"></option>
    </select>
</div>

引用 Reference link

关于java - 使用 thymeleaf 在 spring mvc 应用程序中从数据库生成 html 选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913517/

相关文章:

java - 如何将动态网站(java,spring)作为另一个网站(java)中的网页加载

java - 使用 spring、hibernate 和 scala,有没有比 dbunit 更好的加载测试数据的方法?

spring - @Transactional(readOnly = true) 导致 LazyInitializationException

java - 频繁关闭和打开 hibernate session 是个好主意吗?

java - Tomcat 7 内的 Web 应用程序在 12-18 小时后停止响应

java - 在tomcat 6.0中从jar文件读取静态资源时如何减少linux上打开文件句柄的数量?

java - 如何使用java搜索json文件中的任意单词

java - 如何拦截来自 Openfire 服务器的 Ping 消息?

java - 是否可以从 java 运行导出命令?

java - 如何将数据库表中的空字段映射为 double ?