社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
一、问题描述
现有如下数据,结构是List<Map<String,Object>>,并且Map中还嵌套了Map
需要在页面上显示出来,效果如下:
二、代码实现
StudentController.java
@Controller
@RequestMapping("studentMgmt")
public class StudentController {
@RequestMapping("queryStudentInfo")
public String queryStudentInfo(Model model) {
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
Map<String, Object> student = new HashMap<String, Object>(){{
put("sid", "101");
put("sname", "张三");
put("sage", "20");
put("scourse", new HashMap<String, String>(){{
put("cname", "语文,数学,英语");
put("cscore", "93,95,98");
}});
}};
resultList.add(student);
student = new HashMap<String, Object>(){{
put("sid", "102");
put("sname", "李四");
put("sage", "30");
put("scourse", new HashMap<String, String>(){{
put("cname", "物理,化学,生物");
put("cscore", "92,93,97");
}});
}};
resultList.add(student);
model.addAttribute("resultList", resultList);
return "student/studentInfo";
}
}
studentInfo.html(完整路径 /resources/templates/student/studentInfo.html)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>学生信息</title>
<style type="text/css">
table {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
table thead th {
border: 1px solid black;
}
table tbody td {
border: 1px solid black;
}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<thead>
<th>序号</th>
<th>学生id</th>
<th>学生姓名</th>
<th>学生年龄</th>
<th>学生课程-课程列表</th>
<th>学生课程-课程分数</th>
</thead>
<tbody>
<tr th:each="entries,stat:${resultList}" th:style="'background-color:'+@{${stat.odd}?'#F2F2F2'}">
<td th:text="${stat.count}"></td>
<td th:text="${entries['sid']}"></td>
<td th:text="${entries['sname']}"></td>
<td th:text="${entries['sage']}"></td>
<!-- 写法一:
<td th:text="${entries['scourse']['cname']}"></td>
<td th:text="${entries['scourse']['cscore']}"></td>-->
<!-- 写法二:
<td th:text="*{entries['scourse']['cname']}"></td>
<td th:text="*{entries['scourse']['cscore']}"></td>-->
<!-- 写法三:-->
<td th:object="${entries['scourse']}">
<span th:text="*{['cname']}"></span>
</td>
<td th:object="${entries['scourse']}">
<span th:text="*{['cscore']}"></span>
</td>
</tr>
</tbody>
</table>
</body>
</html>
补充:
注意*{}(选择表达式)和${}(变量表达式)的区别:选择表达式计算的是选定的对象(th:object),变量表达式计算的是整个环境变量映射(写法一和写法三)
如果没有选定的对象,选择表达式和变量表达式效果是一样的(写法一和写法二)
参考链接:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!