在專案開發中,資料分頁是常見需求。本文記錄一套基於 Spring MVC 的手動分頁實作方案,包含控制層邏輯、配置檔設定與前端頁面渲染。
透過 @Value 從配置檔讀取每頁筆數,控制器方法接收查詢條件與頁碼參數:
@Value("#{configProperties['schoolPageSize']}")
private String schoolPageSize;
@RequestMapping(value="/schoolList")
public ModelAndView schoolList(School school, String page) {
int pageSize = Integer.valueOf(schoolPageSize).intValue();
List<School> schoolList = schoolService.findSchoolList(school);
ModelAndView modelAndView = new ModelAndView();
int schoolNum = schoolList.size();
modelAndView.addObject("SchoolNum", schoolNum);
int pageTimes = (schoolNum % pageSize == 0) ? schoolNum / pageSize : schoolNum / pageSize + 1;
modelAndView.addObject("pageTimes", pageTimes);
if (page == null) page = "1";
int startRow = (Integer.parseInt(page) - 1) * pageSize;
List<School> schools = schoolService.getschoolByPage(startRow, pageSize);
modelAndView.addObject("currentPage", Integer.parseInt(page));
modelAndView.addObject("schools", schools);
modelAndView.setViewName("school/schoolList");
return modelAndView;
}
在 springmvc.xml 中配置屬性檔讀取:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:value.properties</value>
</list>
</property>
</bean>
value.properties 內容:
schoolPageSize=5
使用 JSTL 標籤庫渲染分頁導航,包含首頁、上一頁、頁碼、下一頁、尾頁:
<div class="pagging">
<div class="left">共${SchoolNum}條記錄</div>
<div class="right">
<c:if test="${currentPage == 1}">
<span class="disabled"><< 前一頁</span>
</c:if>
<c:if test="${currentPage != 1}">
<a href="school/schoolList.action?page=${currentPage-1}"><< 前一頁</a>
</c:if>
<c:if test="${currentPage == 1}">
<span class="current">1</span>
</c:if>
<c:if test="${currentPage != 1}">
<a href="school/schoolList.action?page=1">1</a>
</c:if>
<!-- 頁碼迴圈邏輯 -->
<%
for(int i=1; i<pageTimes; i++) {
request.setAttribute("page", i+1);
%>
<c:if test="${currentPage == page}">
<span class="current"><%=i+1%></span>
</c:if>
<c:if test="${currentPage != page}">
<a href="school/schoolList.action?page=<%=i+1%>"><%=i+1%></a>
</c:if>
<% } %>
<c:if test="${currentPage == pageTimes}">
<span class="disabled">後一頁 >></span>
</c:if>
<c:if test="${currentPage != pageTimes}">
<a href="school/schoolList.action?page=${currentPage+1}">後一頁 >></a>
</c:if>
</div>
</div>
startRow = (page - 1) * pageSize 計算資料庫查詢起始位置pageTimes = (total % pageSize == 0) ? total/pageSize : total/pageSize + 1page)