web開發中經常需要用到分頁,我然來的做法是每次需要分頁時都把代碼copy一份,比如有10個頁面有分頁,那麼我分頁的代碼就有10個版本.這樣導緻代碼的重用性太低了.
那麼如何解決呢?
把分頁的頁面和邏輯抽取出來,提高代碼品質和重用性.
(1)分頁的頁面抽取出來

<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<table style="height: 35px">
<tr>
<td nowrap="nowrap" style="width: 6%">
<td nowrap="nowrap" style="width: 63%"><span>共<s:property
value="view.totalrecords" />條記錄, 目前第 <s:if
test="view.totalpages==0">0</s:if> <s:else>
<s:property value="view.currentpage" />
</s:else>/ <s:property value="view.totalpages" />頁, 每頁<s:property
value="view.recordsperpage" />條記錄
</span></td>
<td nowrap="nowrap">
<button type="button" class="btn btn-info" style="padding: 1px 10px"
onclick="topagefirst(${param.action})">首頁</button>
onclick="topagepre(${param.action})">上一頁</button>
onclick="topagenext(${param.action})">下一頁</button>
onclick="topagelast(${param.action})">尾頁</button>
onclick="topagego(${param.action})">轉</button>
<s:if test="view.totalpages==0">
<input id="view.currentpage"
name="view.currentpage" size="5"
style="margin-bottom: 0px; width: 50px; ime-mode: disabled; text-align: right; padding: 0px 1px 0px 0px; height: 20px; display: inline-block"
value="0" />
</s:if> <s:else>
<s:textfield cssclass="form-control" id="view.currentpage"
onkeypress="return onlynumber(event);" onpaste="return false;"
/>
</s:else>
<input type="hidden" id="view.thispage" value="<s:property value='view.currentpage' />" />
<s:hidden id="view.totalpages" name="view.totalpages"></s:hidden>
<s:hidden id="view.ascdesc" name="view.ascdesc"></s:hidden>
<s:hidden id="view.sortkey" name="view.sortkey"></s:hidden>
</td>
<td nowrap="nowrap"><span>頁</span></td>
</tr>
</table>
(2)在需要分頁的頁面中引入上述jsp檔案

<s:include value="/web-inf/jsp/pagebottom.jsp">
<s:param name="action">usercoupon.query</s:param>
</s:include>
注意:必須包含在form表單中
(3)在背景action中

public string execute() throws exception {
reservecondition();
int start = (integer.parseint(view.getcurrentpage()) - 1)
* view.getrecordsperpage();
int count = 0;
detachedcriteria clientversiondc = detachedcriteria
.forclass(user.class);
condition(clientversiondc);
list list = new arraylist();
count = this.userservice.listbydetachedcriteria(list,
clientversiondc, start, view.getrecordsperpage());
view.setrecordlist(list);
queryresultlist = new arraylist();
queryresultlist.addall(view.getrecordlist());
view.settotalrecords(count);
int totalpages = pageutil.gettotalpages(view.gettotalrecords(),
view.getrecordsperpage());
view.settotalpages(string.valueof(totalpages));
return "list";
}
在js中聲明方法時,要注意,左邊是錯誤的