springmvc 分页查询的简单实现示例代码
程序员文章站
2024-03-09 11:29:47
目前较常用的分页实现办法有两种:
1.每次翻页都修改sql,向sql传入相关参数去数据库实时查出该页的数据并显示。
2.查出数据库某张表的全部数据,再通过在业务...
目前较常用的分页实现办法有两种:
1.每次翻页都修改sql,向sql传入相关参数去数据库实时查出该页的数据并显示。
2.查出数据库某张表的全部数据,再通过在业务逻辑里面进行处理去取得某些数据并显示。
对于数据量并不大的简单的管理系统而言,第一种实现方法相对来说容易使用较少的代码实现分页这一功能,本文也正是为大家介绍这种方法:
代码片段:
1,page.java
package com.cm.contract.common; import org.apache.commons.lang.stringutils; import org.apache.commons.lang.builder.tostringbuilder; /**分页类 * @author fengwei * @date 2016-5-23 */ public class page implements java.io.serializable{ private static final long serialversionuid = 1l; //前一页 private boolean hasprepage; //后一页 private boolean hasnextpage; //每页显示多少条:默认20条 private long everypage = 20l; //总页数 private long totalpage; //当前第多少页:默认第1页 private long currentpage = 1l; //开始下标 private long beginindex; //结束下标 private long endinindex; //总共多少条 private long totalcount; //排序列名 private string sortname; //排序状态 private string sortstate; //排序信息 private string sortinfo; //是否排序 private boolean sort = false; private string defaultinfo = " "; public string getdefaultinfo() { return defaultinfo; } public void setdefaultinfo(string defaultinfo) { this.defaultinfo = defaultinfo; } public string getsortinfo() { return sortinfo; } public void setsortinfo(string sortinfo) { this.sortinfo = sortinfo; } public string getsortname() { return sortname; } public void setsortname(string sortname) { setpagesortstate(sortname); } public string getsortstate() { return sortstate; } public void setsortstate(string sortstate) { this.sortstate = sortstate; } public page() { } /** * 常用,用于计算分页 * */ public page(long totalrecords){ this.totalcount = totalrecords; settotalpage(gettotalpage(totalrecords)); } /** * 设置每页显示多少条时使用 * */ public page(long everypage,long totalrecords){ this.everypage = everypage; this.totalcount = totalrecords; settotalpage(gettotalpage(totalrecords)); } /** * @param state 状态码 * @param value 到第多少页或者设置每页显示多少条或者为排序列名 */ public void pagestate(int index,string value) { sort = false; switch (index) { case 0 :seteverypage(long.parselong(value));break; case 1 :first();break; case 2: previous();break; case 3: next();break; case 4: last();break; case 5: sort = true;sort(value);break; case 6 ://到指定第多少页 setcurrentpage(long.parselong(value)); break; } } /** * 最前一页 */ private void first() { currentpage = 1l; } private void previous() { currentpage--; } private void next() { currentpage++; } private void last() { currentpage = totalpage; } private void sort(string sortname) { //设置排序状态 setpagesortstate(sortname); } /** * 计算总页数 * */ private long gettotalpage(long totalrecords) { long totalpage = 0l; everypage = everypage == null ? 10l : everypage; if (totalrecords % everypage == 0) totalpage = totalrecords / everypage; else { totalpage = totalrecords / everypage + 1; } return totalpage; } public long getbeginindex() { this.beginindex = (currentpage - 1) * everypage; return this.beginindex; } public void setbeginindex(long beginindex) { this.beginindex = beginindex; } public long getcurrentpage() { this.currentpage = currentpage == 0 ? 1 : currentpage; return this.currentpage; } public void setcurrentpage(long currentpage) { if(0 == currentpage){ currentpage = 1l; } this.currentpage = currentpage; } public long geteverypage() { this.everypage = everypage == 0 ? 10 : everypage; return this.everypage; } public void seteverypage(long everypage) { this.everypage = everypage; } public boolean gethasnextpage() { this.hasnextpage = (currentpage != totalpage) && (totalpage != 0); return this.hasnextpage; } public void sethasnextpage(boolean hasnextpage) { this.hasnextpage = hasnextpage; } public boolean gethasprepage() { this.hasprepage = currentpage != 1; return this.hasprepage; } public void sethasprepage(boolean hasprepage) { this.hasprepage = hasprepage; } public long gettotalpage() { return this.totalpage; } public void settotalpage(long totalpage) { if(this.currentpage > totalpage){ this.currentpage = totalpage; } this.totalpage = totalpage; } public long gettotalcount() { return this.totalcount; } public void settotalcount(long totalcount) { settotalpage(gettotalpage(totalcount)); this.totalcount = totalcount; } @override public string tostring() { return tostringbuilder.reflectiontostring(this); } /** * 设置排序状态 * */ private void setpagesortstate(string newpagesortname){ //判断之前的排序字段是否为空 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(); } public boolean issort() { return sort; } public void setsort(boolean sort) { this.sort = sort; } public long getendinindex() { this.endinindex = (currentpage) * everypage; return endinindex; } public void setendinindex(long endinindex) { this.endinindex = endinindex; } }
2.pagestate.java
package com.cm.contract.common; import org.apache.commons.lang.stringutils; /**分页状态类 * @author fengwei * @date 2016-5-23 */ public enum pagestate { /** * 设置每页显示多少条 * */ setpage, /** * 首页 * */ first, /** * 向前一页 * */ previous, /** * 向后一页 * */ next, /** * 末页 * */ last, /** * 排序 * */ sort, /** * 到第多少页 * */ gopage; /** * @param value 索引名称 * @return 返回索引下标 */ 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
/** * 分页工具类 * @author fengwei * @date 2016-5-23 */ 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"; /** * 初始化分页类 * @param initpagesql 未分页的查询sql * @param totalcount 总行数 * @param index 分页状态 * @param value 只有在设置每页显示多少条时,值不会null,其它为null */ public static page inintpage(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); /**获取session中的分页类,方便保存页面分页状态*/ page = sessionpage; page.seteverypage(everpage); page.settotalcount(totalcount); } return page; } /** * 当页点击:首页,前一页,后一页,末页,排序,到第多少页时进行分页操作 * @param index 分页状态 * @param value 排序字段名或者到第多少页 */ public static page execpage(int index,string value,page sessionpage){ page page = sessionpage; /**调用方法进行分页计算*/ page.pagestate(index,value); return page; } }
4.defaultcontroller.java 此部分可以灵活使用
package com.cm.contract.common; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import org.springframework.web.bind.annotation.modelattribute; /** * 提取公用的request和response title:defaultcontroller descrption: * * @author fengwei * @date 2016-5-6下午3:30:32 */ public class defaultcontroller { /** * oracel的三层分页语句 子类在展现数据前,进行分页计算! * * @param querysql * 查询的sql语句,未进行分页 * @param totalcount * 根据查询sql获取的总条数 * @param columnnamedescorasc * 列名+排序方式 : id desc or asc */ protected page executepage(httpservletrequest request, long totalcount) { if (null == totalcount) { totalcount = 0l; } /** 页面状态,这个状态是分页自带的,与业务无关 */ string pageaction = request.getparameter("pageaction"); string value = request.getparameter("pagekey"); /** 获取下标判断分页状态 */ int index = pagestate.getordinal(pageaction); page page = null; /** * index < 1 只有二种状态 1 当首次调用时,分页状态类中没有值为 null 返回 -1 2 当页面设置每页显示多少条: * index=0,当每页显示多少条时,分页类要重新计算 * */ page sessionpage = getpage(request); if (index < 1) { page = pageutil.inintpage(totalcount, index, value, sessionpage); } else { page = pageutil.execpage(index, value, sessionpage); } setsession(request, page); return page; } private page getpage(httpservletrequest request) { page page = (page) request.getsession().getattribute( pageutil.session_page_key); if (page == null) { page = new page(); } return page; } private void setsession(httpservletrequest request, page page) { request.getsession().setattribute(pageutil.session_page_key, page); } }
使用方法:
5,controller.java
/** * model 添加的分页条件 * executepage 方法写在工具类中 * @param model */ @controller public class cmlogcontroller extends defaultcontroller { @requestmapping("index.do") public modelandview userinto(modelmap model, string username) { namestr = username; model.addattribute("username", namestr); // 分页数 long totalcount = logservice.pagecounts(model); // 分页显示 page page = 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()); modelandview mv = new modelandview(); // 分页查询 loglist = logservice.pagelist(model); mv.addobject("loglist", loglist); mv.setviewname("/jsp/log"); return mv; }}
6.maybatis中几条查询语句
//分页查询 <select id="pagelist" parametertype="map" resultmap="baseresultmap"> select ttt.* from(select tt.*,rownum rn from(select * from cm_log <where> <if test="username != null and username != ''"> <!-- 特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。 在开发时使用: $,方便调试sql,发布时使用: # --> and username like '%${username}%' </if> <if test="type != null and type != ''"> <!-- 特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。 在开发时使用: $,方便调试sql,发布时使用: # --> and type = #{type,jdbctype=varchar} </if> </where> order by ${ordername} ${descasc} )tt)ttt <where> <if test="startindex != null and startindex != ''"> rn > ${startindex} </if> <if test="endindex != null and endindex != ''"> <![cdata[ and rn <= ${endindex} ]]> </if> </where> </select> // 分页数 <select id="pagecounts" parametertype="map" resulttype="long"> select count(*) from cm_log <where> <if test="username != null and username != ''"> and username like '%${username}%' </if> </where> </select>
7.前台页面index.jsp
//只需在页面布局添加该div //username 为条件 // <jsp:param name="url" value="/log/index.do?"/> 不带条件的方式 问号必须存在 <body > <div align="right" style="height: 20"> <jsp:include page="/jsp/page.jsp"> <jsp:param name="url" value="/log/index.do?username=${username }"/> </jsp:include> </div> </body >
8,引用的page.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <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"> ${urlparams } 共${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&pagekey='+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&pagekey='+everypage+'${urlparams}'; a.setattribute("onclick",''); a.click("return false"); } function sortpage(sortname){ var a = document.getelementbyid("indexpagehref"); a.href = '${pathurl}&pageaction=sort&pagekey='+sortname+'${urlparams}'; a.setattribute("onclick",''); a.click("return false"); } </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。