请不要对我的问题进行评分,因为我是JSP / JavaEE的新手..
我看了很多关于JSTL,Pagination的教程,但是我无法做出适当的想法来进行分页......有没有一种方法来执行分页......?
在我的程序中,我使用java类从数据库中检索搜索结果的记录,并将它们放入ArrayList并将ArrayList返回给Servlet。然后将收到的ArrayList对象分配给像这样的应用程序属性
request.setAttribute("Results", results_List);
然后使用请求调度程序,我正在加载显示jsp页面的结果。
RequestDispatcher rd = request.getRequestDispatcher("searchresults.jsp");
rd.forward(request, response);
告诉我下一步做分页我的搜索结果..
答案 0 :(得分:7)
在Servlet中,我们首先获取'page'参数的值并将其存储在'page'变量中。我们希望每页显示五(5)条记录,我们将其作为参数传递给viewAllEmployees(offset,5)。我们在请求范围中存储三个属性并将请求转发到JSP页面;
Servlet类:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = 1;
int recordsPerPage = 5;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
EmployeeDAO dao = new EmployeeDAO();
List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,
recordsPerPage);
int noOfRecords = dao.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("employeeList", list);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("employee.jsp");
view.forward(request, response);
}
Jsp文件:
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<th>Emp ID</th>
<th>Emp Name</th>
<th>Salary</th>
<th>Dept Name</th>
</tr>
<c:forEach var="employee" items="${employeeList}">
<tr>
<td>${employee.employeeId}</td>
<td>${employee.employeeName}</td>
<td>${employee.salary}</td>
<td>${employee.deptName}</td>
</tr>
</c:forEach>
</table>
<%--For displaying Previous link except for the 1st page --%>
<c:if test="${currentPage != 1}">
<td><a href="employee.do?page=${currentPage - 1}">Previous</a></td>
</c:if>
<%--For displaying Page numbers.
The when condition does not display a link for the current page--%>
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<c:forEach begin="1" end="${noOfPages}" var="i">
<c:choose>
<c:when test="${currentPage eq i}">
<td>${i}</td>
</c:when>
<c:otherwise>
<td><a href="employee.do?page=${i}">${i}</a></td>
</c:otherwise>
</c:choose>
</c:forEach>
</tr>
</table>
<%--For displaying Next link --%>
<c:if test="${currentPage lt noOfPages}">
<td><a href="employee.do?page=${currentPage + 1}">Next</a></td>
</c:if>