Thymeleaf是一个很好用的模板引擎, 可以完全取代JSP
需求
数据库中有张名为commanders的表存有多个人的信息, 现在通过后台去查询整张表, 返回一个集合, 要求使用thymeleaf动态的把集合内容以表格的形式展示在网页上
表的内容如下
后台关键代码如下
@Controller
public class HelloController {
@Autowired
CommanderDao commanderDao;
@RequestMapping("/list")
public String queryAll(Map<String, Object> map) {
//查询整张表, 返回List集合
List<Commander> commanders = commanderDao.queryAll();
map.put("commanders", commanders); //存入map中
return "myView";
}
}
说明: 查询整张表, 返回一个List集合, 里面每一个元素都被封装成Commander类(对应表中每一行记录), 再将集合存入map中(为了之后让thymeleaf遍历取出来), 最后返回myView视图
循环遍历
myView.html
<table class="layui-table">
<colgroup>
<col width="150">
<col width="200">
<col>
</colgroup>
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr th:each="commander:${commanders}">
<td th:text="${commander.getId()}"></td>
<td th:text="${commander.getName()}"></td>
<td th:text="${commander.getAge()}"></td>
</tr>
</tbody>
</table>
循环遍历类似于foreach循环, 通过${}的形式把之前存入map中的元素取出来, 取出的List集合中每一个元素都是一个Commander对象, 于是调用它的get()方法依次把属性取出来. 注意:集合中有多少个元素表格中就会自动生成多少行
看一下结果
没毛病