关于利用jstl标签遍历集合属性的用法

 在MVC模型中,通常会利用Model或者Map将模型数据存放到Request域或者Session域中,以便WEB项目中在前端页面获取后端控制器中放入的模型数据,关于集合属性常常都要需要在页面渲染成表格的形式,下面记录一下关于前端页面渲染集合属性到表格的用法:
1. 加入jstl需要的jar包:jstl-1.2.jar和standard-1.1.2.jar。由于用SpringMVC比较多,好像Struts2是自带的。
2. 页面引入jstl标签:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3. 使用标签进行循环遍历:
<c:if test="${empty requestScope.emps}">
    没有任何员工信息!
</c:if>
<c:if test="${!empty requestScope.emps}">
    <table border="1" cellpadding="10" cellspacing="0">
        <tr>
            <th>ID</th>
            <th>LastName</th>
            <th>Email</th>
            <th>Gender</th>
            <th>Department</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
        <!--循环遍历集合属性,其中items是获取集合,var是给获取的集合取个别名,方便书写-->
        <c:forEach items="${requestScope.emps}" var="employees">
            <tr>
                <td>${employees.id}</td>
                <td align="center">${employees.lastName}</td>
                <td>${employees.email}</td>
                <!--判断解析-->
                <td align="center">${employees.gender == 0 ? 'female' : 'male'}</td>
                <td align="center">${employees.department.departmentName}</td>
                <td><a href="">Edit</a> </td>
                <td><a href="">Delete</a> </td>
            </tr>
        </c:forEach>
    </table>
</c:if>

【注意】上面是将查询的Employee类型的集合放到Request域中,其中Employee中有几个需要说明的属性:gender属性是Integer类型,0表示female,1表示male,departemnt表示的是Employee所属的部门(多对一的关联关系)。

猜你喜欢

转载自blog.csdn.net/jacksonary/article/details/79538177