springmvc 分页查询的简单实现示例代码
目前较常用的分页实现办法有两种:
1.每次翻页都修改SQL,向SQL传入相关参数去数据库实时查出该页的数据并显示。
2.查出数据库某张表的全部数据,再通过在业务逻辑里面进行处理去取得某些数据并显示。
对于数据量并不大的简单的管理系统而言,第一种实现方法相对来说容易使用较少的代码实现分页这一功能,本文也正是为大家介绍这种方法:
代码片段:
1,Page.java
packagecom.cm.contract.common; importorg.apache.commons.lang.StringUtils; importorg.apache.commons.lang.builder.ToStringBuilder; /**分页类 *@authorFENGWEI *@date2016-5-23 */ publicclassPageimplementsjava.io.Serializable{ privatestaticfinallongserialVersionUID=1L; //前一页 privateBooleanhasPrePage; //后一页 privateBooleanhasNextPage; //每页显示多少条:默认20条 privateLongeveryPage=20L; //总页数 privateLongtotalPage; //当前第多少页:默认第1页 privateLongcurrentPage=1L; //开始下标 privateLongbeginIndex; //结束下标 privateLongendinIndex; //总共多少条 privateLongtotalCount; //排序列名 privateStringsortName; //排序状态 privateStringsortState; //排序信息 privateStringsortInfo; //是否排序 privateBooleansort=false; privateStringdefaultInfo=""; publicStringgetDefaultInfo(){ returndefaultInfo; } publicvoidsetDefaultInfo(StringdefaultInfo){ this.defaultInfo=defaultInfo; } publicStringgetSortInfo(){ returnsortInfo; } publicvoidsetSortInfo(StringsortInfo){ this.sortInfo=sortInfo; } publicStringgetSortName(){ returnsortName; } publicvoidsetSortName(StringsortName){ setPageSortState(sortName); } publicStringgetSortState(){ returnsortState; } publicvoidsetSortState(StringsortState){ this.sortState=sortState; } publicPage(){ } /** *常用,用于计算分页 **/ publicPage(LongtotalRecords){ this.totalCount=totalRecords; setTotalPage(getTotalPage(totalRecords)); } /** *设置每页显示多少条时使用 **/ publicPage(LongeveryPage,LongtotalRecords){ this.everyPage=everyPage; this.totalCount=totalRecords; setTotalPage(getTotalPage(totalRecords)); } /** *@paramstate状态码 *@paramvalue到第多少页或者设置每页显示多少条或者为排序列名 */ publicvoidpageState(intindex,Stringvalue){ sort=false; switch(index){ case0:setEveryPage(Long.parseLong(value));break; case1:first();break; case2:previous();break; case3:next();break; case4:last();break; case5:sort=true;sort(value);break; case6://到指定第多少页 setCurrentPage(Long.parseLong(value)); break; } } /** *最前一页 */ privatevoidfirst(){ currentPage=1L; } privatevoidprevious(){ currentPage--; } privatevoidnext(){ currentPage++; } privatevoidlast(){ currentPage=totalPage; } privatevoidsort(StringsortName){ //设置排序状态 setPageSortState(sortName); } /** *计算总页数 **/ privateLonggetTotalPage(LongtotalRecords){ LongtotalPage=0L; everyPage=everyPage==null?10L:everyPage; if(totalRecords%everyPage==0) totalPage=totalRecords/everyPage; else{ totalPage=totalRecords/everyPage+1; } returntotalPage; } publicLonggetBeginIndex(){ this.beginIndex=(currentPage-1)*everyPage; returnthis.beginIndex; } publicvoidsetBeginIndex(LongbeginIndex){ this.beginIndex=beginIndex; } publicLonggetCurrentPage(){ this.currentPage=currentPage==0?1:currentPage; returnthis.currentPage; } publicvoidsetCurrentPage(LongcurrentPage){ if(0==currentPage){ currentPage=1L; } this.currentPage=currentPage; } publicLonggetEveryPage(){ this.everyPage=everyPage==0?10:everyPage; returnthis.everyPage; } publicvoidsetEveryPage(LongeveryPage){ this.everyPage=everyPage; } publicBooleangetHasNextPage(){ this.hasNextPage=(currentPage!=totalPage)&&(totalPage!=0); returnthis.hasNextPage; } publicvoidsetHasNextPage(BooleanhasNextPage){ this.hasNextPage=hasNextPage; } publicBooleangetHasPrePage(){ this.hasPrePage=currentPage!=1; returnthis.hasPrePage; } publicvoidsetHasPrePage(BooleanhasPrePage){ this.hasPrePage=hasPrePage; } publicLonggetTotalPage(){ returnthis.totalPage; } publicvoidsetTotalPage(LongtotalPage){ if(this.currentPage>totalPage){ this.currentPage=totalPage; } this.totalPage=totalPage; } publicLonggetTotalCount(){ returnthis.totalCount; } publicvoidsetTotalCount(LongtotalCount){ setTotalPage(getTotalPage(totalCount)); this.totalCount=totalCount; } @Override publicStringtoString(){ returnToStringBuilder.reflectionToString(this); } /** *设置排序状态 **/ privatevoidsetPageSortState(StringnewPageSortName){ //判断之前的排序字段是否为空 if(StringUtils.isEmpty(sortName)){ //默认排序为升序 this.sortState=PageUtil.ASC; this.sortInfo=PageUtil.PAGE_ASC; }else{ if(StringUtils.equalsIgnoreCase(newPageSortName,sortName)){ //判断sortState排序状态值 if(StringUtils.equalsIgnoreCase(sortState,PageUtil.ASC)){ this.sortState=PageUtil.DESC; this.sortInfo=PageUtil.PAGE_DESC; }else{ this.sortState=PageUtil.ASC; this.sortInfo=PageUtil.PAGE_ASC; } }else{ //默认 this.sortState=PageUtil.ASC; this.sortInfo=PageUtil.PAGE_ASC; } } sortName=newPageSortName.toLowerCase(); } publicBooleanisSort(){ returnsort; } publicvoidsetSort(Booleansort){ this.sort=sort; } publicLonggetEndinIndex(){ this.endinIndex=(currentPage)*everyPage; returnendinIndex; } publicvoidsetEndinIndex(LongendinIndex){ this.endinIndex=endinIndex; } }
2.PageState.java
packagecom.cm.contract.common; importorg.apache.commons.lang.StringUtils; /**分页状态类 *@authorFENGWEI *@date2016-5-23 */ publicenumPageState{ /** *设置每页显示多少条 **/ SETPAGE, /** *首页 **/ FIRST, /** *向前一页 **/ PREVIOUS, /** *向后一页 **/ NEXT, /** *末页 **/ LAST, /** *排序 **/ SORT, /** *到第多少页 **/ GOPAGE; /** *@paramvalue索引名称 *@return返回索引下标 */ publicstaticintgetOrdinal(Stringvalue){ intindex=-1; if(StringUtils.isEmpty(value)){ returnindex; } StringnewValue=StringUtils.trim(value).toUpperCase(); try{ index=valueOf(newValue).ordinal(); }catch(IllegalArgumentExceptione){} returnindex; } }
3.PageUtil.java
/** *分页工具类 *@authorFENGWEI *@date2016-5-23 */ publicclassPageUtil{ publicstaticfinalStringASC="asc"; publicstaticfinalStringDESC="desc"; publicstaticfinalStringPAGE_DESC="↓"; publicstaticfinalStringPAGE_ASC="↑"; publicstaticfinalStringPAGE_NULL=""; publicstaticfinalStringSESSION_PAGE_KEY="page"; /** *初始化分页类 *@paraminitPageSql未分页的查询SQL *@paramtotalCount总行数 *@paramindex分页状态 *@paramvalue只有在设置每页显示多少条时,值不会NULL,其它为NULL */ publicstaticPageinintPage(LongtotalCount,Integerindex,Stringvalue,PagesessionPage){ Pagepage=null; if(index<0){ page=newPage(totalCount); }else{ /**每页显示多少条*/ LongeverPage=null==value?10:Long.parseLong(value); /**获取Session中的分页类,方便保存页面分页状态*/ page=sessionPage; page.setEveryPage(everPage); page.setTotalCount(totalCount); } returnpage; } /** *当页点击:首页,前一页,后一页,末页,排序,到第多少页时进行分页操作 *@paramindex分页状态 *@paramvalue排序字段名或者到第多少页 */ publicstaticPageexecPage(intindex,Stringvalue,PagesessionPage){ Pagepage=sessionPage; /**调用方法进行分页计算*/ page.pageState(index,value); returnpage; } }
4.DefaultController.java 此部分可以灵活使用
packagecom.cm.contract.common; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; importorg.springframework.web.bind.annotation.ModelAttribute; /** *提取公用的request和responseTitle:DefaultControllerDescrption: * *@authorFENGWEI *@date2016-5-6下午3:30:32 */ publicclassDefaultController{ /** *oracel的三层分页语句子类在展现数据前,进行分页计算! * *@paramquerySql *查询的SQL语句,未进行分页 *@paramtotalCount *根据查询SQL获取的总条数 *@paramcolumnNameDescOrAsc *列名+排序方式:IDDESCorASC */ protectedPageexecutePage(HttpServletRequestrequest,LongtotalCount){ if(null==totalCount){ totalCount=0L; } /**页面状态,这个状态是分页自带的,与业务无关*/ StringpageAction=request.getParameter("pageAction"); Stringvalue=request.getParameter("pageKey"); /**获取下标判断分页状态*/ intindex=PageState.getOrdinal(pageAction); Pagepage=null; /** *index<1只有二种状态1当首次调用时,分页状态类中没有值为NULL返回-12当页面设置每页显示多少条: *index=0,当每页显示多少条时,分页类要重新计算 **/ PagesessionPage=getPage(request); if(index<1){ page=PageUtil.inintPage(totalCount,index,value,sessionPage); }else{ page=PageUtil.execPage(index,value,sessionPage); } setSession(request,page); returnpage; } privatePagegetPage(HttpServletRequestrequest){ Pagepage=(Page)request.getSession().getAttribute( PageUtil.SESSION_PAGE_KEY); if(page==null){ page=newPage(); } returnpage; } privatevoidsetSession(HttpServletRequestrequest,Pagepage){ request.getSession().setAttribute(PageUtil.SESSION_PAGE_KEY,page); } }
使用方法:
5,Controller.java
/** *model添加的分页条件 *executePage方法写在工具类中 *@parammodel */ @Controller publicclassCMLogControllerextendsDefaultController{ @RequestMapping("index.do") publicModelAndViewuserInto(ModelMapmodel,Stringusername){ nameStr=username; model.addAttribute("username",nameStr); //分页数 LongtotalCount=logService.pageCounts(model); //分页显示 Pagepage=executePage(request,totalCount); if(page.isSort()){ model.put("orderName",page.getSortName()); model.put("descAsc",page.getSortState()); }else{ model.put("orderName","logtime"); model.put("descAsc","desc"); } model.put("startIndex",page.getBeginIndex()); model.put("endIndex",page.getEndinIndex()); ModelAndViewmv=newModelAndView(); //分页查询 logList=logService.pageList(model); mv.addObject("logList",logList); mv.setViewName("/jsp/log"); returnmv; }}
6.maybatis中几条查询语句
//分页查询 <selectid="pageList"parameterType="map"resultMap="BaseResultMap"> selectttt.*from(selecttt.*,rownumrnfrom(select*fromCM_LOG <where> <iftest="username!=nullandusername!=''"> <!-- 特别提醒一下,$只是字符串拼接,所以要特别小心sql注入问题。 在开发时使用:$,方便调试sql,发布时使用:# --> andusernamelike'%${username}%' </if> <iftest="type!=nullandtype!=''"> <!-- 特别提醒一下,$只是字符串拼接,所以要特别小心sql注入问题。 在开发时使用:$,方便调试sql,发布时使用:# --> ANDTYPE=#{type,jdbcType=VARCHAR} </if> </where> orderby${orderName}${descAsc})tt)ttt <where> <iftest="startIndex!=nullandstartIndex!=''"> rn>${startIndex} </if> <iftest="endIndex!=nullandendIndex!=''"> <![CDATA[andrn<=${endIndex}]]> </if> </where> </select> //分页数 <selectid="pageCounts"parameterType="map"resultType="long"> selectcount(*)fromCM_LOG <where> <iftest="username!=nullandusername!=''"> andusernamelike'%${username}%' </if> </where> </select>
7.前台页面index.jsp
//只需在页面布局添加该div //username为条件 //<jsp:paramname="url"value="/log/index.do?"/>不带条件的方式问号必须存在 <body> <divalign="right"style="height:20"> <jsp:includepage="/jsp/page.jsp"> <jsp:paramname="url"value="/log/index.do?username=${username}"/> </jsp:include> </div> </body>
8,引用的Page.jsp
<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <c:setvar="page"value="${sessionScope.page}"/> <c:setvar="path"value="${pageContext.request.contextPath}"/> <c:setvar="url"value="${param.url}"/> <c:setvar="urlParams"value="${param.urlParams}"/> <c:setvar="pathurl"value="${path}/${url}"/> <tr> <tdcolspan="5"> ${urlParams} 共${page.totalCount}条记录共${page.totalPage}页每页显示${page.everyPage}条 当前第${page.currentPage}页 <c:choose> <c:whentest="${page.hasPrePageeqfalse}"> <<首页<上页 </c:when> <c:otherwise> <ahref="${pathurl}&pageAction=first${urlParams}"><<首页</a> <ahref="${pathurl}&pageAction=previous${urlParams}"/><上一页</a> </c:otherwise> </c:choose> || <c:choose> <c:whentest="${page.hasNextPageeqfalse}"> 下页>尾页>> </c:when> <c:otherwise> <ahref="${pathurl}&pageAction=next${urlParams}">下一页></a> <ahref="${pathurl}&pageAction=last${urlParams}">末页>></a> </c:otherwise> </c:choose> <SELECTname="indexChange"id="indexChange" onchange="getCurrentPage(this.value);"> <c:forEachvar="index"begin="1"end="${page.totalPage}"step="1"> <optionvalue="${index}"${page.currentPageeqindex?"selected":""}> 第${index}页 </option> </c:forEach> </SELECT> 每页显示:<selectname="everyPage"id="everyPage"onchange="setEveryPage(this.value);"> <c:forEachvar="pageCount"begin="5"end="${page.totalCount}"step="5"> <optionvalue="${pageCount}"${page.everyPageeqpageCount?"selected":""}> ${pageCount}条 </option> </c:forEach> </select> </td> </tr> <divstyle='display:none'> <aclass=listlinkid="indexPageHref"href='#'></a> </div> <script> functiongetCurrentPage(index){ vara=document.getElementById("indexPageHref"); a.href='${pathurl}&pageAction=gopage&pageKey='+index+'${urlParams}'; a.setAttribute("onclick",''); a.click("returnfalse"); } functionsetEveryPage(everyPage){ vara=document.getElementById("indexPageHref"); varcurrentPage=document.getElementById('indexChange').value; a.href='${pathurl}&pageAction=setpage&pageKey='+everyPage+'${urlParams}'; a.setAttribute("onclick",''); a.click("returnfalse"); } functionsortPage(sortName){ vara=document.getElementById("indexPageHref"); a.href='${pathurl}&pageAction=sort&pageKey='+sortName+'${urlParams}'; a.setAttribute("onclick",''); a.click("returnfalse"); } </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。