■ Table of contents 1, at the beginning 2, page number logic 3, code example
■ Introduction When I made a search site, I took a lot of time to display the page number, so I will post it thought. I would appreciate it if you could refer to it. (Since it is an example, please let me know if there is an improvement or better code)
■ Page number logic
When the page is 1, the numbers up to 5 are displayed, and "..." is displayed in between to display the last number.
When the page number is 5 or more, the first page, the front two page numbers, the back two, and the last number are displayed.
If the page is (last page-3), the first page, the last page, and the previous page are displayed.
■ Code example (jsp) The href of the a tag is the code without the link. Since there is no sense in naming variables and constants, please let me know if you have a good name.
<%
//Number of pages / Variable declaration of current page
int currentPage;
int lastPageNum;
//Variable assignment
currentPage = 5;
lastPageNum = 9;
//Constant declaration
final int FIRST_PAGE = 1;
final int FIRST_HALF_CHECK = 5;
final int LAST_HALF_CHECK = 4;
final int BEFORE_AND_AFTER = 2;
%>
<section>
<div class="pageLeft">
<%if(currentPage != FIRST_PAGE){ %>
<a href="">To the previous page</a>
<%} %>
</div>
<div class="pageCenter">
<%if(currentPage >= FIRST_HALF_CHECK){ %>
<a href="">1</a>
…
<%} %>
<%if(currentPage < FIRST_HALF_CHECK){ %>
<%for(int i = 1; i <= FIRST_HALF_CHECK; i++){ %>
<%if(i <= lastPageNum){ %>
//Branch whether to include a tag or not (currently page does not include a tag)
<%if(i == currentPage){ %>
<span><%=i %></span>
<%}else{ %>
<a href=""><%=i %></a>
<%} %>
<%} %>
<%} %>
<%}else if(lastPageNum - currentPage < LAST_HALF_CHECK){ %>
<%for(int i = lastPageNum - LAST_HALF_CHECK; i <= lastPageNum; i++){ %>
<%if(i > 0){ %>
//Branch whether to include a tag or not (currently page does not include a tag)
<%if(i == currentPage){ %>
<span><%=i %></span>
<%}else{ %>
<a href=""><%=i %></a>
<%} %>
<%} %>
<%} %>
<%}else{ %>
<%for(int i = currentPage - BEFORE_AND_AFTER; i <= currentPage + BEFORE_AND_AFTER; i++){ %>
//Branch whether to include a tag or not (currently page does not include a tag)
<%if(i == currentPage){ %>
<span><%=i %></span>
<%}else{ %>
<a href=""><%=i %></a>
<%} %>
<%} %>
<%} %>
<%if(lastPageNum - currentPage >= LAST_HALF_CHECK){ %>
…<a href=""><%=lastPageNum %></a>
<%} %>
</div>
<div class="pageRight">
<%if(currentPage != lastPageNum){ %>
<a href="">to the next page</a>
<%} %>
</div>
</section>
■ Summary I wrote it because I got stuck in page number logic once on the search site. I think there are better ways and improvements, so I would appreciate it if you could let me know.
Recommended Posts