我们知道在新增页面如果有下拉框就直接选择就好,但是在编辑页面的下拉框要默认选中在新增页面选择的值,即数据回显。我也是第一次使用Thymeleaf模板引擎,虽然使用JSP多了,Thymeleaf上手快使用也方便,但是还是会有一些小问题。最初,我想使用th:selected,如下方式:
<option th:each="user : ${users}" th:text="${user.userName}" th:value="${user.userId}" th:selected="${user.userId eq userId}">
</option>
但是,这种方式并没有效果。经过后续的测试,需要eq一个固定值,或者th:selected="${user.userId} == ${userId}",是有效果的。
或者,在<select>标签上使用th:field="*{userName}"也可以,如下:
<select name="userName" class="form-control" th:field="*{userName}">
<option th:each="user : ${users}" th:text="${user.userName}" th:value="${user.userId}">
</option>
</select>
于是,在Thymeleaf中使用<select>标签数据回显问题就很好的解决了。