![](/img/trans.png)
[英]How to send an object from a thymeleaf form to MVC spring boot controller
[英]Thymeleaf + Spring MVC - How to persist values from a list or enum on a form?
我有一个显示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>
希望它可以帮到某人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.