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中声明方法时,要注意,左边是错误的