我有一个显示 sql 连接列表的页面。该表中的字段之一是 databaseType,它在枚举中定义:
public enum SqlDatabaseType {
NONE("None"),
MySQL("MySql"),
SQLSERVER("SQLServer");
为了创建和编辑对象,我使用以下内容填充选择框:
<label th:for="databaseType">SQL Database Type:</label>
<select>
<option th:each="databaseType : ${T(b.c.m.h.m.SqlDatabaseType).values()}"
th:value="${databaseType}"
th:field="*{databaseType}"
th:text="${databaseType.databaseType}">
</option>
</select>
填充该表单的 DTO 对象是:
public class SqlPojo {
private String id;
private String description;
private SqlDatabaseType databaseType;
private String url;
private String port;
private String database;
private String username;
private String password;
// getter and setters
问题是所有 String 字段都被持久化,但不是复杂类型。
列出所有已创建对象的表定义为:
<table class="table table-bordered table-striped">
<thead>
<tr>
<td style="text-align: center">description</td>
<td style="text-align: center">databaseType</td>
<td style="text-align: center">url</td>
<td style="text-align: center">port</td>
<td style="text-align: center">database</td>
<td style="text-align: center">username</td>
<td style="text-align: center">actions</td>
</tr>
</thead>
<tbody>
<tr th:each="pojo : ${pojoList}">
<td style="text-align: center" th:text="${pojo.description}"/>
<td style="text-align: center" th:text="${pojo.databaseType}"/>
<td style="text-align: center" th:text="${pojo.url}"/>
<td style="text-align: center" th:text="${pojo.port}"/>
<td style="text-align: center" th:text="${pojo.database}"/>
<td style="text-align: center" th:text="${pojo.username}"/>
<td style="text-align: center" >
<a th:href="@{/sql/edit(id=${pojo.id})}">
<img width="20px" height="20px" alt="edit" th:src="@{/assets/img/edit.png}" />
</a>
<a th:href="@{/sql/remove(id=${pojo.id})}">
<img width="20px" height="20px" alt="remove" th:src="@{/assets/img/delete.png}" />
</a>
</td>
</tr>
</tbody>
</table>
渲染出来的是:
在开始使用 Thymeleaf 之前,我使用的是 JSP,表定义非常相似,我毫无问题地获得了 databaseType
值。
切换到 Thymeleaf 呈现了一些不错的视觉效果,但也有一些问题,例如枚举和列表的问题(将在另一个问题中提及)。在这种情况下最好的解决方案是什么?定义转换器?如果是,怎么办?
最佳答案
对于枚举,我通过以下方式让它工作:
<div class="form-group">
<label th:for="databaseType">SQL Database Type:</label>
<select class="form-control" th:field="*{{databaseType}}">
<option th:each="databaseType : ${T(b.c.m.h.m.SqlDatabaseType).values()}"
th:value="${{databaseType}}"
th:selected="${databaseType == T(b.c.m.h.m.SqlDatabaseType)}"
th:text="${databaseType.databaseType}">
</option>
</select>
</div>
对于列表,解决方案有点不同:
<div class="form-group">
<label th:for="ftpConnection">FTP Connection:</label>
<select class="form-control" name="ftpId" >
<option th:each="ftpConnection : ${ftpList}"
th:value="${ftpConnection.getId()}"
th:text="${ftpConnection.getDescription()}">
</option>
</select>
</div>
希望对大家有帮助!
关于java - Thymeleaf + Spring MVC - 如何在表单上保留列表或枚举中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36525564/