一.遍历数据举例
1)、获取后端数据
//查询所有员工列表
@GetMapping("/emps")
public String list(Model mode){
Collection<Employee> employees = employeeDao.getAll();
mode.addAttribute("emps",employees);
return "emp/list";
}
2)、html遍历显示数据
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[emp.lastName]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender}==0?'女':'男'"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}"></td>
<td>
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<button th:attr="del-uri=@{/emp/}+${emp.id} " class="btn btn-sm btn-danger delete-btn">删除</button>
</td>
</tr>
一.保存/编辑共用举例
<form th:action="@{/emp}" method="post">
<!--发送put请求修改员工数据-->
<!--
1.SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
2.页面创建一个post表单
3.页面创建一个input项,name="_method",值就是我们指定的请求方式
-->
<input type="hidden" name="_method" value="put" th:if="${emp!=null}">
<input type="hidden" name="id" value="" th:if="${emp!=null}" th:value="${emp.id}">
<div class="form-group">
<label>姓名</label>
<input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}">
</div>
<div class="form-group">
<label>邮箱</label>
<input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${emp!=null}?${emp.email}">
</div>
<div class="form-group">
<label>性别</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>部门</label>
<select class="form-control" name="department.id">
<option th:each="dept:${depts}" th:text="${dept.departmentName}" th:value="${dept.id}" th:selected="${emp!=null}?${emp.department.id==dept.id}">1</option>
</select>
</div>
<div class="form-group">
<label>生日</label>
<input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}">
</div>
<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
<a class="btn btn-dark" th:href="@{/emps}" role="button">取消</a>
</form>