參考資料
1 ssh分頁(多個例子)
http://useryouyou.iteye.com/blog/593954
2 ssh2分頁例子
http://459104018-qq-com.iteye.com/blog/467196
3 ssh2分頁
http://blog.csdn.net/shmily2038/archive/2009/12/28/5090044.aspx
注意事項:
此示例是在:Struts2.2+Spring3.1+Hibernate3.6整合(登陸示例及CRUD操做)基礎上加的分頁功能:
http://liuzidong.iteye.com/blog/935493
實現功能:分頁,排序,設置每頁顯示多少條,轉到第多少頁
調用說明:
1 導入只須要:com.liuzd.page包下的類或者將page.jar加入WEB-INF/lib下也行^_^
2 Struts2前臺類實現: BaseAction父類
3 在子類方法中調用父類提供的方法:
Page page = executePage(querySql,totalCount," id desc ");
須要傳遞三個參數就好了: querySql(查詢sql語句), totalCount(總行數),
" id desc "(排序的列名與排序方式)
4 返回分頁數據
List<User> users = this.userService.getUserListByPage(page);
5 在spring配置文件中請保持有: jdbcTemplate與hibernateTemplate這二個Bean的名字,不然dbUtil類不能使用
6 具體可參見:四的說明
一 運行環境:XP+Myeclipse6.6+WebLogic92+Oracle10g
二 工程相關圖片:
1 DEMO圖片
2 工程代碼圖片
3 page.jar圖片
三 此示例是在:
Struts2.2+Spring3.1+Hibernate3.6整合(登陸示例及CRUD操做)基礎上加的分頁功能:
http://liuzidong.iteye.com/blog/935493,jar包在此頁面中下載
四 關注類及頁面:
1 BaseAction類(可能你在項目有其它的父類要使用,只要關注這個類中的: protected Page executePage(String querySql,Long totalCount,String columnNameDescOrAsc)方法就好了,方法中的參數不用修改,它來自於page.jsp,你可拷貝這個方法到你的父類中就實現了分頁功能,分頁類詳見註釋)
2 UserAction子類(只關注:方法:userList()中的調用方式)
3 UserDAOImpl類(關注方法:public List<User> getUserListByPage(final Page page) )
4 userList.jsp頁面 html
- <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
- <c:set var="page" value="${sessionScope.page}" />
在排序處: java
- <font color='red'>${page.sortName eq "username" ? page.sortInfo :page.defaultInfo}</font>
在下面加上: web
- <jsp:include page="/page/page.jsp">
- <jsp:param name="url" value="userAction!userList.action" />
- <!-- 演示傳值:要用%26 -->
- <jsp:param name="urlParams" value="%26age=2" />
- </jsp:include>
四 要關注的類與頁面
1 BaseAction.java
spring
- package com.liuzd.common;
-
- import java.util.Map;
-
- import javax.servlet.http.HttpServletRequest;
-
- import org.apache.struts2.ServletActionContext;
- import org.apache.struts2.interceptor.SessionAware;
-
- import com.liuzd.page.Page;
- import com.liuzd.page.PageUtil;
- import com.liuzd.page.PageState;
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionSupport;
-
- public class BaseAction extends ActionSupport implements SessionAware{
-
- private static final long serialVersionUID = 1L;
-
- public void setSession(Map<String, Object> sessionMap) {
-
- }
-
- protected Map<String,Object> getMapSession(){
- return (Map<String,Object>)ActionContext.getContext().getSession();
- }
-
- protected Object getMapSessionGet(String key){
- return getMapSession().get(key);
- }
-
- protected void setMapSessionPut(String key,Object value){
- getMapSession().put(key, value);
- }
-
-
- protected HttpServletRequest getRequest(){
- return ServletActionContext.getRequest ();
- }
-
-
- protected javax.servlet.http.HttpSession getSession(){
- return getRequest().getSession();
- }
-
-
- protected void setRequestAttribute(String attribute,Object attrValue){
- getRequest().setAttribute(attribute, attrValue);
- }
-
-
- protected Object getRequestAttribute(String attribute){
- return getRequest().getAttribute(attribute);
- }
-
-
- protected void setSessionAttribute(String attribute,Object attrValue){
- getSession().setAttribute(attribute, attrValue);
- }
-
-
- protected Object getSessionAttribute(String attribute){
- return getSession().getAttribute(attribute);
- }
-
-
-
- protected Page executePage(String querySql,Long totalCount,String columnNameDescOrAsc){
- String oracleSql = PageUtil.createQuerySql(querySql,columnNameDescOrAsc);
- if(null == totalCount){
- totalCount = 0L;
- }
-
- String pageAction = getRequest().getParameter("pageAction");
- String value = null;
-
- int index = PageState.getOrdinal(pageAction);
- if(0 == index){
-
- value = getRequest().getParameter("everyPage");
- }
-
- Page page = null;
-
- if(index < 1){
- page = PageUtil.inintPage(oracleSql,totalCount,index,value,getPage());
- }else{
-
- if(5 == index){
- value = getRequest().getParameter("sortName");
-
- }else if(6 == index){
- value = getRequest().getParameter("currentPage");
- }
- page = PageUtil.execPage(index,value,getPage());
- }
- setSession(page);
- return page;
- }
-
- private Page getPage() {
- Page page = (Page)getSession().getAttribute(PageUtil.SESSION_PAGE_KEY);
- if(page == null){
- page = new Page();
- }
- return page;
- }
-
- private void setSession(Page page) {
- getSession().setAttribute(PageUtil.SESSION_PAGE_KEY,page);
- }
- }
2 UserAction.java
sql
3 UserDAOImpl.java
apache
5 JSP引用
session
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
- <c:set var="page" value="${sessionScope.page}" />
- <html>
- <head>
- <title>用戶集合</title>
- </head>
-
- <body>
- <table width="60%" border="1" cellpadding="0" align="center">
- <thead>
- <tr>
- <th style="cursor: hand;" title="按姓名進行排序" onclick="sortPage('username')" valign="top">
- 姓名<font color='red'>${page.sortName eq "username" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" title="按年齡進行排序" onclick="sortPage('age')" valign="top">
- 年齡<font color='red'>${page.sortName eq "age" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" title="按性別進行排序" onclick="sortPage('sex')" valign="top">
- 性別<font color='red'>${page.sortName eq "sex" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" title="按地址進行排序" onclick="sortPage('address')" valign="top">
- 地址<font color='red'>${page.sortName eq "address" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" >
- 操做
- </th>
- </tr>
- </thead>
- <tbody>
- <!--
- <s:iterator value="#request.userList" status="status" >
- <tr align="center">
- <td><s:property value="username"/></td>
- <td><s:property value="age"/></td>
- <td><s:property value="sex"/></td>
- <td><s:property value="address"/></td>
- <td>
- <s:a href="userAction!addUser.action">添加</s:a> | <s:a href="userAction!loadUser.action?user.id=%{id}">編輯</s:a> |
- <a href="<s:url action="userAction!delUser.action"><s:param name="user.id" value="id"/></s:url>">刪除</a>
- </td>
- </tr>
- </s:iterator>
- -->
-
- <c:forEach items="${requestScope.userList}" var="user">
- <tr align="center">
- <td>
- ${user.username}
- </td>
- <td>
- ${user.age}
- </td>
- <td>
- ${user.sex eq 1 ? "男" : user.sex eq 2 ? "女" : "未知"}
- </td>
- <td>
- ${user.address}
- </td>
- <td>
- <a
- href="${pageContext.request.contextPath}/userAction!addUser.action">添加</a>
- |
- <a
- href="${pageContext.request.contextPath}/userAction!loadUser.action?user.id=${user.id}">編輯</a>
- |
- <a
- href="${pageContext.request.contextPath}/userAction!delUser.action?user.id=${user.id}">刪除</a>
- </td>
- </tr>
- </c:forEach>
-
- <jsp:include page="page.jsp">
- <jsp:param name="url" value="userAction!userList.action" />
- <!-- 演示傳值:要用%26 -->
- <jsp:param name="urlParams" value="%26age=2" />
- </jsp:include>
-
- </tbody>
- </table>
- <br>
- <a href="${pageContext.request.contextPath}/Login.jsp">返回</a>
- <br>
- <s:debug></s:debug>
- </body>
- </html>
五 你不須要關注的分頁類與JSP頁面,可在附件下載jar與源碼
1 Page.java
oracle
2 PageState.java
app
- package com.liuzd.page;
-
- import org.apache.commons.lang3.StringUtils;
-
- public enum PageState {
-
-
- SETPAGE,
-
- FIRST,
-
- PREVIOUS,
-
- NEXT,
-
- LAST,
-
- SORT,
-
- GOPAGE;
-
-
-
- public static int getOrdinal(String value) {
- int index = -1;
- if (StringUtils.isEmpty(value)) {
- return index;
- }
- String newValue = StringUtils.trim(value).toUpperCase();
- try {
- index = valueOf(newValue).ordinal();
- } catch (IllegalArgumentException e) {}
- return index;
- }
- }
3 PageUtil.java
eclipse
- package com.liuzd.page;
-
- public class PageUtil {
-
- public static final String ASC = "asc";
- public static final String DESC = "desc";
- public static final String PAGE_DESC = "↓";
- public static final String PAGE_ASC = "↑";
- public static final String PAGE_NULL = " ";
- public static final String SESSION_PAGE_KEY = "page";
-
-
-
- public static String getPageQuerySql(String querySql,Long beginIndex, Long endinIndex) {
- if(querySql.indexOf("where rn>") != -1 && querySql.indexOf("and rn<=") != -1){
- return querySql.toUpperCase();
- }
- return new java.lang.StringBuffer().append(querySql).append(" where rn>").append(beginIndex).append(" and rn<=").append(endinIndex).toString().toUpperCase();
- }
-
-
- @SuppressWarnings("unused")
- public static String createQuerySql(String querySql, String orderByName) {
- StringBuilder sql = new StringBuilder();
- sql.append("select ttt.* from(select tt.*,rownum rn from(");
- sql.append(querySql);
- if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderByName)) {
- sql.append(" order by ").append(orderByName);
- }
- sql.append(" )tt)ttt ");
- return sql.toString();
- }
-
-
- public static String getSortDescOrAsc(String querySql) {
-
- querySql = querySql.toUpperCase();
- String temp = "ORDER BY";
- int orderIndex = querySql.lastIndexOf(temp);
- String newsql = querySql.substring(orderIndex);
- String temp2 = ")";
- int lastIndex = newsql.indexOf(temp2);
- String orderByName = newsql.substring(temp.length(),lastIndex).trim();
- return orderByName;
- }
-
-
- public static Page inintPage(String initPageSql,Long totalCount,Integer index,String value,Page sessionPage){
- Page page = null;
- if(index < 0){
- page = new Page(totalCount);
- }else{
-
- Long everPage = null == value ? 10 : Long.parseLong(value);
-
- page = sessionPage;
- page.setEveryPage(everPage);
- page.setTotalCount(totalCount);
- }
- page.setInitQuerySql(initPageSql);
-
- String querySql = getPageQuerySql(initPageSql,page.getBeginIndex(), page.getEndinIndex());
-
- page.setQuerySql(querySql);
-
- return page;
- }
-
-
-
-
-
- public static Page execPage(int index,String value,Page sessionPage){
-
- Page page = sessionPage;
-
-
- page.pageState(index,value);
-
- String initPageSql = page.getInitQuerySql();
-
- String querySql = getPageQuerySql(initPageSql,page.getBeginIndex(), page.getEndinIndex());
-
-
- if (page.isSort() == true) {
- String sortName = page.getSortName();
- if (null != sortName) {
-
- String descAsc = page.getSortState();
-
- String sortNameDescAsc = (" " + sortName + " " + descAsc).toUpperCase();
-
- String getOldSortName = PageUtil.getSortDescOrAsc(querySql);
-
- querySql = querySql.replace(getOldSortName,sortNameDescAsc);
- }
- }
- page.setQuerySql(querySql);
- return page;
- }
-
- }
4 page.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
- <c:set var="page" value="${sessionScope.page}" />
- <c:set var="path" value="${pageContext.request.contextPath}" />
- <c:set var="url" value="${param.url}" />
- <c:set var="urlParams" value="${param.urlParams}" />
- <c:set var="pathurl" value="${path}/${url}" />
- <tr>
- <td colspan="5">
- 共${page.totalCount}條記錄 共${page.totalPage}頁 每頁顯示${page.everyPage}條
- 當前第${page.currentPage}頁
- <c:choose>
- <c:when test="${page.hasPrePage eq false}">
- <<首頁 <上頁
- </c:when>
- <c:otherwise>
- <a href="${pathurl}?&pageAction=first${urlParams}"><<首頁 </a>
- <a href="${pathurl}?pageAction=previous${urlParams}" /><上一頁</a>
- </c:otherwise>
- </c:choose>
- ||
- <c:choose>
- <c:when test="${page.hasNextPage eq false}">
- 下頁> 尾頁>>
- </c:when>
- <c:otherwise>
- <a href="${pathurl}?&pageAction=next${urlParams}">下一頁> </a>
- <a href="${pathurl}?pageAction=last${urlParams}" />末頁>></a>
- </c:otherwise>
- </c:choose>
-
- <SELECT name="indexChange" id="indexChange"
- onchange="getCurrentPage(this.value);">
- <c:forEach var="index" begin="1" end="${page.totalPage}" step="1">
- <option value="${index}" ${page.currentPage eq index ? "selected" : ""}>
- 第${index}頁
- </option>
- </c:forEach>
- </SELECT>
-
- 每頁顯示:<select name="everyPage" id="everyPage" onchange="setEveryPage(this.value);">
- <c:forEach var="pageCount" begin="5" end="${page.totalCount}" step="5">
- <option value="${pageCount}" ${page.everyPage eq pageCount ? "selected" : ""}>
- ${pageCount}條
- </option>
- </c:forEach>
- </select>
- </td>
- </tr>
- <div style='display: none'>
- <a class=listlink id="indexPageHref" href='#'></a>
- </div>
- <script>
- function getCurrentPage(index){
- var a = document.getElementById("indexPageHref");
- a.href = '${pathurl}?pageAction=gopage¤tPage='+index+'${urlParams}';
- a.setAttribute("onclick",'');
- a.click("return false");
- }
- function setEveryPage(everyPage){
- var a = document.getElementById("indexPageHref");
- var currentPage = document.getElementById('indexChange').value;
- a.href = '${pathurl}?pageAction=setpage&everyPage='+everyPage+'${urlParams}';
- a.setAttribute("onclick",'');
- a.click("return false");
- }
- function sortPage(sortName){
- var a = document.getElementById("indexPageHref");
- a.href = '${pathurl}?pageAction=sort&sortName='+sortName+'${urlParams}';
- a.setAttribute("onclick",'');
- a.click("return false");
- }
- </script>
- 原地址是 http://liuzidong.iteye.com/blog/1042172