jstl forEach逆序輸出list
阿新 • • 發佈:2018-12-31
最近在寫程式碼,有一個功能,需要把後臺傳遞到前臺的資料逆序輸出,本想通過Collections.reverse(list);對list中的資料進行逆序排列後再傳遞到後臺,但想到for迴圈都可以逆序輸出,就想JSTL是否也有可
以進行相關操作,結果搞了半個多鍾才寫出了下面一段程式碼
- <%@pageimport="com.jasper.domain.Person"%>
- <%@pageimport="java.util.List"%>
- <%@pageimport="java.util.ArrayList"%>
- <%@ page language="java" contentType=
- pageEncoding="UTF-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
- <%
- //Person物件中有兩個屬性,age和name
- List<Person> persons = new ArrayList<Person>();
- Person person1 = new Person();
- person1.setAge(12);
- person1.setName("小明");
- persons.add(person1);
- Person person2 = new Person();
- person2.setAge(13);
- person2.setName("阿飛");
- persons.add(person2);
- request.setAttribute("persons"
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>JSTL逆序迴圈</title>
- </head>
- <body>
- <div>正序</div>
- <div>
- <table>
- <thead>
- <tr>
- <th>年齡</th>
- <th>姓名</th>
- </tr>
- </thead>
- <tbody>
- <c:forEach var="person" items="${persons }">
- <tr>
- <td>${person.age }</td>
- <td>${person.name }</td>
- </tr>
- </c:forEach>
- </tbody>
- </table>
- </div>
- <br />
- <div>逆序</div>
- <div>
- <table>
- <thead>
- <tr>
- <th>年齡</th>
- <th>姓名</th>
- </tr>
- </thead>
- <tbody>
- <c:set var="startIndex" value="${fn:length(persons)-1 }"></c:set>
- <c:forEach var="person" items="${persons }" varStatus="status">
- <tr>
- <td>${persons[startIndex - status.index].age }</td>
- <td>${persons[startIndex - status.index].name }</td>
- </tr>
- </c:forEach>
- </tbody>
- </table>
- </div>
- <br />
- </body>
- </html>
以進行相關操作,結果搞了半個多鍾才寫出了下面一段程式碼