【struts2+hibernate+spring项目实战】分页功能的完整的实现(通用分页、基类实现)
生活随笔
收集整理的這篇文章主要介紹了
【struts2+hibernate+spring项目实战】分页功能的完整的实现(通用分页、基类实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、概述
今天自己做了個項目練練,然后有一些分頁的功能,自己把分頁的功能做了一個簡單的總結,然后,為了以后能夠方便自己的開發,做了一個baseDao的實現。
二、代碼實現
2.1、分頁的實體類pageBean
package org.sihai.utils;import java.util.List;public class PageBean {//當前頁數private Integer currentPage;//總記錄數private Integer totalCount;//每頁顯示條數private Integer pageSize;//總頁數private Integer totalPage;//分頁列表數據private List list;public PageBean(Integer currentPage, Integer totalCount, Integer pageSize) {this.totalCount = totalCount;this.pageSize = pageSize;this.currentPage = currentPage;if(this.currentPage == null){//如頁面沒有指定顯示那一頁.顯示第一頁.this.currentPage = 1;}if(this.pageSize == null){//如果每頁顯示條數沒有指定,默認每頁顯示3條this.pageSize = 3;}//計算總頁數this.totalPage = (this.totalCount+this.pageSize-1)/this.pageSize;//判斷當前頁數是否超出范圍//不能小于1if(this.currentPage < 1){this.currentPage = 1;}//不能大于總頁數if(this.currentPage > this.totalPage){this.currentPage = this.totalPage;}}//計算起始索引public int getStart(){return (this.currentPage-1)*this.pageSize;}public Integer getCurrentPage() {return currentPage;}public void setCurrentPage(Integer currentPage) {this.currentPage = currentPage;}public Integer getTotalCount() {return totalCount;}public void setTotalCount(Integer totalCount) {this.totalCount = totalCount;}public Integer getPageSize() {return pageSize;}public void setPageSize(Integer pageSize) {this.pageSize = pageSize;}public Integer getTotalPage() {return totalPage;}public void setTotalPage(Integer totalPage) {this.totalPage = totalPage;}public List getList() {return list;}public void setList(List list) {this.list = list;}}2.2、Action的實現
package org.sihai.web.action;import org.apache.commons.lang3.StringUtils; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions;import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven;import org.sihai.domain.user; import org.sihai.domain.User; import org.sihai.service.userService; import org.sihai.service.UserService; import org.sihai.utils.PageBean;public class userAction extends ActionSupport implements ModelDriven<user> {private user user = new user();private userService cs;private Integer currentPage;private Integer pageSize;public String list() throws Exception {//封裝離線查詢對象DetachedCriteria dc = DetachedCriteria.forClass(user.class);//判斷并封裝參數if(StringUtils.isNotBlank(user.getuser_name())){dc.add(Restrictions.like("user_name", "%"+user.getuser_name()+"%"));}//1 調用Service查詢分頁數據(PageBean)PageBean pb = cs.getPageBean(dc,currentPage,pageSize);//2 將PageBean放入request域,轉發到列表頁面顯示ActionContext.getContext().put("pageBean", pb);return "list";}@Overridepublic user getModel() {return user;}public void setCs(userService cs) {this.cs = cs;}public Integer getCurrentPage() {return currentPage;}public void setCurrentPage(Integer currentPage) {this.currentPage = currentPage;}public Integer getPageSize() {return pageSize;}public void setPageSize(Integer pageSize) {this.pageSize = pageSize;}}2.3、service的實現
package org.sihai.service.impl;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.sihai.dao.userDao; import org.sihai.domain.user; import org.sihai.service.userService; import org.sihai.utils.PageBean;public class userServiceImpl implements userService {private userDao cd;@Overridepublic PageBean getPageBean(DetachedCriteria dc, Integer currentPage, Integer pageSize) {//1 調用Dao查詢總記錄數Integer totalCount = cd.getTotalCount(dc);//2 創建PageBean對象PageBean pb = new PageBean(currentPage, totalCount, pageSize);//3 調用Dao查詢分頁列表數據List<user> list = cd.getPageList(dc,pb.getStart(),pb.getPageSize());//4 列表數據放入pageBean中.并返回pb.setList(list);return pb;}public void setCd(userDao cd) {this.cd = cd;}}2.4、baseDao的具體實現(通用基類)
package org.sihai.dao.impl;import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List;import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import org.sihai.dao.BaseDao; import org.sihai.domain.user;public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {private Class clazz;//用于接收運行期泛型類型public BaseDaoImpl() {//獲得當前類型的帶有泛型類型的父類ParameterizedType ptClass = (ParameterizedType) this.getClass().getGenericSuperclass();//獲得運行期的泛型類型clazz = (Class) ptClass.getActualTypeArguments()[0];}@Overridepublic void save(T t) {getHibernateTemplate().save(t);}@Overridepublic void delete(T t) {getHibernateTemplate().delete(t);}@Overridepublic void delete(Serializable id) {T t = this.getById(id);//先取,再刪getHibernateTemplate().delete(t);}@Overridepublic void update(T t) {getHibernateTemplate().update(t);}@Overridepublic T getById(Serializable id) {return (T) getHibernateTemplate().get(clazz, id);}@Overridepublic Integer getTotalCount(DetachedCriteria dc) {//設置查詢的聚合函數,總記錄數dc.setProjection(Projections.rowCount());List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(dc);//清空之前設置的聚合函數dc.setProjection(null);if(list!=null && list.size()>0){Long count = list.get(0);return count.intValue();}else{return null;}}@Overridepublic List<T> getPageList(DetachedCriteria dc, Integer start, Integer pageSize) {List<T> list = (List<T>) getHibernateTemplate().findByCriteria(dc, start, pageSize);return list;}}2.5、baseService的具體實現
package org.sihai.qualitycontrol.util.base;import java.io.Serializable; import java.util.List;import org.springframework.transaction.annotation.Transactional; @Transactional public interface BaseEbi<T> {public void save(T t);public void update(T t);public void delete(T t);public List<T> getAll();public T get(Serializable uuid);public List<T> getAll(BaseQueryModel qm, Integer pageNum,Integer pageCount);public Integer getCount(BaseQueryModel qm);}2.6、baseAction的具體實現
package org.sihai.qualitycontrol.util.base;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import org.sihai.qualitycontrol.auth.emp.vo.EmpModel;import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport;public class BaseAction extends ActionSupport{public static final String LIST = "list";public static final String TO_LIST = "toList";public static final String INPUT = "input";public Integer pageNum = 1;public Integer pageCount = 10;public Integer maxPageNum;public Integer dataTotal;public String getActionName(){//動態//DepAction ->dep//EmpAction ->empString actionName = this.getClass().getSimpleName();//DepAction ->DepString temp = actionName.substring(0, actionName.length()-6);//Dep ->dep OrderDetailAction ->orderDetail orderdetailreturn temp.substring(0,1).toLowerCase()+temp.substring(1);}protected void setDataTotal(int dataTotal){this.dataTotal = dataTotal ;maxPageNum = (dataTotal + pageCount -1) / pageCount;}protected void put(String name,Object obj){ActionContext.getContext().put(name,obj);}protected Object get(String name){return ActionContext.getContext().get(name);}protected void putSession(String name,Object obj){ActionContext.getContext().getSession().put(name,obj);}protected Object getSession(String name){return ActionContext.getContext().getSession().get(name);}protected EmpModel getLogin(){return (EmpModel) getSession(EmpModel.EMP_LOGIN_USER_OBJECT_NAME);}protected HttpServletRequest getRequest(){return ServletActionContext.getRequest();}protected HttpServletResponse getResponse(){return ServletActionContext.getResponse();}}2.7、頁面的實現
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <TITLE>客戶列表</TITLE> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <LINK href="${pageContext.request.contextPath }/css/Style.css" type=text/css rel=stylesheet> <LINK href="${pageContext.request.contextPath }/css/Manage.css" type=text/cssrel=stylesheet> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script> <SCRIPT language=javascript>function changePage(pageNum){//1 將頁碼的值放入對應表單隱藏域中$("#currentPageInput").val(pageNum);//2 提交表單$("#pageForm").submit();};function changePageSize(pageSize){//1 將頁碼的值放入對應表單隱藏域中$("#pageSizeInput").val(pageSize);//2 提交表單$("#pageForm").submit();}; </SCRIPT><META content="MSHTML 6.00.2900.3492" name=GENERATOR> </HEAD> <BODY><TABLE cellSpacing=0 cellPadding=0 width="98%" border=0><TBODY><TR><TD width=15><IMG src="${pageContext.request.contextPath }/images/new_019.jpg"border=0></TD><TD width="100%" background="${pageContext.request.contextPath }/images/new_020.jpg"height=20></TD><TD width=15><IMG src="${pageContext.request.contextPath }/images/new_021.jpg"border=0></TD></TR></TBODY></TABLE><TABLE cellSpacing=0 cellPadding=0 width="98%" border=0><TBODY><TR><TD width=15 background=${pageContext.request.contextPath }/images/new_022.jpg><IMG src="${pageContext.request.contextPath }/images/new_022.jpg" border=0></TD><TD vAlign=top width="100%" bgColor=#ffffff><TABLE cellSpacing=0 cellPadding=5 width="100%" border=0><TR><TD class=manageHead>當前位置:客戶管理 > 客戶列表</TD></TR><TR><TD height=2></TD></TR></TABLE><TABLE borderColor=#cccccc cellSpacing=0 cellPadding=0width="100%" align=center border=0><TBODY><TR><TD height=25><FORM id="pageForm" name="userForm"action="${pageContext.request.contextPath }/userAction_list"method=post><!-- 隱藏域.當前頁碼 --><input type="hidden" name="currentPage" id="currentPageInput" value="<s:property value="#pageBean.currentPage" />" /><!-- 隱藏域.每頁顯示條數 --><input type="hidden" name="pageSize" id="pageSizeInput" value="<s:property value="#pageBean.pageSize" />" /><TABLE cellSpacing=0 cellPadding=2 border=0><TBODY><TR><TD>客戶名稱:</TD><TD><INPUT class=textbox id=sChannel2style="WIDTH: 80px" maxLength=50 name="user_name" value="${param.user_name}"></TD><TD><INPUT class=button id=sButton2 type=submitvalue=" 篩選 " name=sButton2></TD></TR></TBODY></TABLE></FORM></TD></TR><TR><TD><TABLE id=gridstyle="BORDER-TOP-WIDTH: 0px; FONT-WEIGHT: normal; BORDER-LEFT-WIDTH: 0px; BORDER-LEFT-COLOR: #cccccc; BORDER-BOTTOM-WIDTH: 0px; BORDER-BOTTOM-COLOR: #cccccc; WIDTH: 100%; BORDER-TOP-COLOR: #cccccc; FONT-STYLE: normal; BACKGROUND-COLOR: #cccccc; BORDER-RIGHT-WIDTH: 0px; TEXT-DECORATION: none; BORDER-RIGHT-COLOR: #cccccc"cellSpacing=1 cellPadding=2 rules=all border=0><TBODY><TR style="FONT-WEIGHT: bold; FONT-STYLE: normal; BACKGROUND-COLOR: #eeeeee; TEXT-DECORATION: none"><TD>客戶名稱</TD><TD>客戶級別</TD><TD>客戶來源</TD><TD>聯系人</TD><TD>電話</TD><TD>手機</TD><TD>操作</TD></TR><s:iterator value="#pageBean.list" var="user" ><TR style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none"><TD><s:property value="#user.user_name" /></TD><TD><s:property value="#user.user_level" /></TD><TD><s:property value="#user.user_source" /></TD><TD><s:property value="#user.user_goods" /></TD><TD><s:property value="#user.user_phone" /></TD><TD><s:property value="#user.user_mobile" /></TD><TD><a href="${pageContext.request.contextPath }/userServlet?method=edit&userId=${user.user_id}">修改</a> <a href="${pageContext.request.contextPath }/userServlet?method=delete&userId=${user.user_id}">刪除</a></TD></TR></s:iterator></TBODY></TABLE></TD></TR><TR><TD><SPAN id=pagelink><DIV style="LINE-HEIGHT: 20px; HEIGHT: 20px; TEXT-ALIGN: right">共[<B><s:property value="#pageBean.totalCount" /> </B>]條記錄,[<B><s:property value="#pageBean.totalPage" /></B>]頁,每頁顯示 <%-- changePageSize($('#pageSizeSelect option').filter(':selected').val()) --%> <select name="pageSize" onchange="changePageSize($('#pageSizeSelect option:selected').val())" id="pageSizeSelect" ><option value="3" <s:property value="#pageBean.pageSize==3?'selected':''" /> >3</option><option value="5" <s:property value="#pageBean.pageSize==5?'selected':''" /> >5</option></select>條[<A href="javaScript:void(0)" onclick="changePage(<s:property value='#pageBean.currentPage-1' />)" >前一頁</A>]<B><s:property value="#pageBean.currentPage" /></B>[<A href="javaScript:void(0)" onclick="changePage(<s:property value='#pageBean.currentPage+1' />)" >后一頁</A>] 到<input type="text" size="3" id="page" name="page" value="<s:property value="#pageBean.currentPage" />" />頁<input type="button" value="Go" onclick="changePage($('#page').val())"/></DIV></SPAN></TD></TR></TBODY></TABLE></TD><TD width=15 background="${pageContext.request.contextPath }/images/new_023.jpg"><IMG src="${pageContext.request.contextPath }/images/new_023.jpg" border=0></TD></TR></TBODY></TABLE><TABLE cellSpacing=0 cellPadding=0 width="98%" border=0><TBODY><TR><TD width=15><IMG src="${pageContext.request.contextPath }/images/new_024.jpg"border=0></TD><TD align=middle width="100%"background="${pageContext.request.contextPath }/images/new_025.jpg" height=15></TD><TD width=15><IMG src="${pageContext.request.contextPath }/images/new_026.jpg"border=0></TD></TR></TBODY></TABLE></BODY> </HTML>三、通用分頁實現
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="51%"> </td><td width="13%">共${dataTotal}條記錄<td width="6%"><a id="fir" class="sye">首 頁</a></td><td width="6%"><a id="pre" class="sye">上一頁</a></td><td width="6%"><a id="next" class="sye">下一頁</a></td><td width="6%"><a id="last" class="sye">末 頁</a></td><td width="12%">當前第<span style="color:red;">${pageNum}</span>/${maxPageNum }頁</td></tr> </table> <s:hidden name="pageNum"/> <script type="text/javascript">$(function(){//最大頁=1,都隱藏//第一頁,前2隱藏,后2顯示 //最后一頁,前2顯示,后2隱藏//中間任意,都顯示var pageNum = ${pageNum};var maxPageNum = ${maxPageNum}; if(maxPageNum == 1){$("#fir").css("display","none");$("#pre").css("display","none");$("#next").css("display","none");$("#last").css("display","none");}else if(pageNum == 1){$("#fir").css("display","none");$("#pre").css("display","none");$("#next").css("display","inline");$("#last").css("display","inline");}else if(maxPageNum == pageNum){$("#fir").css("display","inline");$("#pre").css("display","inline");$("#next").css("display","none");$("#last").css("display","none");}else {$("#fir").css("display","inline");$("#pre").css("display","inline");$("#next").css("display","inline");$("#last").css("display","inline");}$("#fir").click(function(){$("[name=pageNum]").val(1);$("form:first").submit();});$("#pre").click(function(){$("[name=pageNum]").val($("[name=pageNum]").val()-1);$("form:first").submit();});//下一頁$("#next").click(function(){//收集頁碼值,將頁碼值設置為指定值,提交表單//獲取原始頁碼值,然后+1,設置回去$("[name=pageNum]").val($("[name=pageNum]").val()*1+1);$("form:first").submit();});$("#last").click(function(){$("[name=pageNum]").val(maxPageNum);$("form:first").submit();});}); </script>四、總結
以前這樣的總結還是比較少的,以至于在以后的開發,很多的模塊的小的東西還需要重新的來思考,很是浪費時間,希望以后能夠堅持。。。
總結
以上是生活随笔為你收集整理的【struts2+hibernate+spring项目实战】分页功能的完整的实现(通用分页、基类实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: svn教程----eclipse的SVN
- 下一篇: 【struts2+hibernate+s