开发者

How to do pagination in JSP?

I have a page which displays a table with some entries which is taken from a method in form of a list from a JPA Entity for the first time.

now I have 3 buttons: previous, accept, next

what I want is when I click the next or previous button, it should show the previous / next entry.

here are some code snippets:

<%!
 Request req=new Request();
 List<pendingRequest> li= req.showDetails();
 int i=0;
 pendingRequest pr=null; %>
<%pr=li.get(i); %>
 <table align="center">
<tr><td><b>Employee Id  :</b></td>开发者_运维问答<td><%=pr.getEmpId()%></td></tr>
<tr><td><b>Name         :</b></td><td><%=pr.getEmpName()%></td></tr>
<tr><td><b>Phone Number :</b></td><td><%=pr.getEmpPhnNo()%></td></tr>
<tr><td><b>Email Id     :</b></td><td><%=pr.getEmpEmail()%></td></tr>
<tr><td><b>Password     :</b></td><td><%=pr.getEmpPassword()%></td></tr>
</table><br><br>

<table align="center">
<tr><td>
<input type="button" value="Previous" onclick="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="Accept" onclick="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="Next" onclick="">
</td></tr>
</table>

can somebody please help me how should I proceed to make it possible?

Thanks in advance.


You should modify your showDetails method to accept two parameters: pageNumber, resultsPerPage.

Then inside your showDetails method you'll have something like this:

/**
 * <code>pageNumber</code> starts from 0
 */
public List<PendingRequest> showDetails(int pageNumber, int resultsPerPage)
{
 Query q = ...
 q.setFirstResult(pageNumber * resultsPerPage);
 q.setMaxResults(resultsPerPage);
 ...
 return q.getResultList();
}

Set the page number at the top of the page:

<%
  int pageNumber = request.getParameter("pageNumber") == null ? 0 : Integer.parseInt(request.getParameter("pageNumber"));
%>

Change the Next and Previous inputs with links (let's suppose your JSP file is named list.jsp):

<a href="list.jsp?pageNumber=<%= pageNumber + 1 %>">Next</a>
<a href="list.jsp?pageNumber=<%= pageNumber - 1 %>">Previous</a>

This needs a little bit of tweaking (e.g. to ensure the pageNumber never becomes less than 0), but overall this is the approach you could take.


What Behrang answered is the inner-working which is fabulous.

Alternatively you can use displaytag.sf.net/ in case you might be trying to reinvent the wheel. The displaytag also allows the user to export the table to pdf and excel format, so you don't need to write extra codes for reporting in some cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜