2つの一般的なページング実装方法があります。
1.ページをターンするたびにSQLを変更し、関連するパラメーターをSQLに渡し、データベースに移動してページのデータをリアルタイムで見つけて表示します。
2。データベースの特定のテーブルのすべてのデータを見つけてから、ビジネスロジックで処理して特定のデータを取得および表示します。
少量のデータを備えた単純な管理システムの場合、最初の実装方法は比較的簡単に使用して、ページングの機能を実装するためにコードを使用できます。この記事では、この方法についても紹介します。
コードスニペット:
1。page.java
パッケージcom.cm.contract.common; org.apache.commons.lang.stringutilsをインポートします。 org.apache.commons.lang.builder.tostringbuilderをインポートします。 / ** Pagination class*@author fengwei*@date 2016-5-23*/ public classページはjava.io.serializable {private static final long serialversionuid = 1l; //前のページprivate boolean hasprepage; //次のページPrivate Boolean HasNextPage; //ページごとに表示されるアイテムの数:デフォルト20のプライベートロングeverypage = 20L; //プライベートロングトータルページの総数。 //現在のページ:デフォルトページ1 private long currentPage = 1L; // subscript Private long beginindexを開始します。 // subscript private long endinindexを終了します。 //プライベートロングトータルカウントの数。 //列名の並べ替えprivate string sortname; //ステータスプライベート文字列SORTSTATEのソート。 //情報の並べ替えプライベート文字列SORTINFO; //プライベートブールのソートをソートするかどうかをソート= false;プライベート文字列defaultInfo = ""; public string getDefaultInfo(){return defaultInfo; } public void setDefaultInfo(String DefaultInfo){this.defaultInfo = defaultInfo; } public string getSortInfo(){return sotedinfo; } 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ページ(long totalRecords){this.totalcount = totalRecords; settotalpage(gettotalpage(TotalRecords)); } / ** *使用 *各ページに表示されるエントリの数を設定するとき * * / publicページ(長いすべてのページ、長い合計レコード){this.EveryPage = EveryPage; this.totalcount = totalRecords; settotalpage(gettotalpage(TotalRecords)); } / *** @param State Status Code* @param値ページに移動または設定するページの数を設定するか、ソート列名として並べ替えるか* / public void pagestate(int index、string value){sort = false; switch(index){case 0:seteverypage(long.parselong(value)); break;ケース1:first(); break;ケース2:前(); break;ケース3:next(); break;ケース4:last(); break;ケース5:sort = true; sort(value); break;ケース6://指定されたページSetCurrentPage(long.Parselong(value));壊す; }} / ***前のページ* / private void first(){currentPage = 1L; } private void forter(){currentPage--; } private void next(){currentPage ++; } private void last(){currentPage = TotalPage; } private void sort(string sortname){//ソートステータスsetPagesOrtState(sortName); } / ***ページの総数を計算* everyPage = EveryPage == null? 10L:すべてのページ。 if(totalRecords%EveryPage == 0)TotalPage = TotalRecords / EveryPage; else {totalpage = totalRecords / EveryPage + 1; } totalpageを返します。 } public long getBeginIndex(){this.beginIndex =(currentPage -1) * EveryPage; this.beginindexを返します。 } public void setBeginIndex(long beginIndex){this.beginIndex = beginIndex; } public long getCurrentPage(){this.currentPage = currentPage == 0? 1:CurrentPage; this.currentPageを返します。 } public void setCurrentPage(long currentPage){if(0 == currentPage){currentPage = 1L; } this.currentPage = currentPage; } public long getEveryPage(){this.EveryPage = EveryPage == 0? 10:すべてのページ。これを返してください。すべてのページ。 } public void seteverypage(long everypage){this.everypage = everypage; } public boolean gethasnextpage(){this.hasnextPage =(currentPage!= TotalPage)&&(TotalPage!= 0); this.hasnextpageを返します。 } public void sethasnextpage(boolean hasnextpage){this.hasnextpage = hasnextpage; } public boolean gethasprepage(){this.hasprepage = currentPage!= 1; this.hasprepageを返します。 } public void sethasprepage(boolean hasprepage){this.hasprepage = hasprepage; } public long gettotalpage(){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 settoTotalcount(long totalcount){settotalPage(getTotalPage(TotalCount)); this.totalcount = totalcount; } @Override public String toString(){return toStringBuilder.ReflectionToString(this); } /***ソートステータスを設定*** /private void setPagesortState(String newPagesortName){//前のソートフィールドが空であるかどうかを判断します(stringutils.isempty(sortname)){//デフォルトのソートはascend this.sortstate = pageutil.asc; this.sortinfo = pageutil.page_asc; } else {if(stringutils.equalsignorecase(newpagesortname、sortname)){// sorttate sorting status value if(stringutils.equalsignorecase(sorttate、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 sistort(){return sort; } public void setSort(boolean sort){this.sort = sort; } public long getEndinIndex(){this.endinindex =(currentPage) * everyPage; endinindexを返します。 } public void setendinindex(long endinindex){this.endinindex = endinindex; }} 2.pagestate.java
パッケージcom.cm.contract.common; org.apache.commons.lang.stringutilsをインポートします。 /**ページネーションステータスクラス* @author fengwei* @date 2016-5-23* /public enum pagestate { /***ページごとに表示するピースの数** /setpage、 /***ホームページ** /***前行く * */ gopage; / *** @param値インデックス名* @return 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合計総数rows* @paramインデックスページングステータス* @param値ページごとに表示される場合のみ、値はnullではない場合、その他はnull*/ public static page intpage、integer in index、in integer index、page parut、null、public static page、null、in integer if(index <0){page = new Page(TotalCount); } else { / **ページごとに表示されるピースの数* / long everpage = null == value? 10:long.parselong(value); / **ページのページングステータスの保存を容易にするために、セッションでページングクラスを取得します*/ page = sessionpage; page.seteverypage(everpage); page.settotalcount(totalcount); }返信ページ; } / ***ページがクリックすると:ホームページ、前のページ、次のページ、最後のページ、ソート、およびページは最初のページ* @param indexページングステータス* @param値ソートフィールド名またはページは最初のページ* / public staticページexecpage(int index、string value、page sessionpage){ページページ= sessionpage; / **ページング計算のメソッドを呼び出します*/ page.pagestate(index、value);返信ページ。 }} 4.DefaultController.javaこの部品は柔軟に使用できます
パッケージcom.cm.contract.common; javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 javax.servlet.http.httpsessionをインポートします。 org.springframework.web.bind.annotation.modelattributeをインポートします。 /** *パブリックリクエストと応答タイトル:DefaultController説明: * * @author fengwei * @date 2016-5-6 3:30:32 pm * /public class defaultcontroller { /** *データを表示する前にページネーション計算を実行します。 * * @param querysql * Query SQLステートメント、paginated * @param totalcount *クエリSQLに基づいて取得したエントリの総数 * @param columnNamedEscorasc *列名 +選別方法:ID DESCまたはASC */保護されたページexecutePage(httpservletrequest、totalcount) } / **ページステータス、このステータスはページ上に構築されており、ビジネスとは何の関係もありません* / string pageAction = request.getParameter( "pageaction");文字列値= request.getParameter( "pagekey"); / **インデックスを取得してページステータスを判断する*/ int index = pagestate.getordinal(pageaction);ページページ= null; / ** index <1 2つの状態のみがあります1 if(index <1){page = pageutil.inintpage(totalcount、index、value、sessionpage); } else {page = pageutil.execpage(index、value、sessionpage); } setSession(リクエスト、ページ);返信ページ。 } private Page getPage(httpservletrequest request){page page =(page)request.getSession()。getattribute(pageutil.session_page_key); if(page == null){page = new page(); }返信ページ; } private void setSession(httpservletrequest request、ページページ){request.getSession()。setAttribute(pageutil.session_page_key、ページ); }}使い方:
5。Controller.java
/ ***モデルによって追加されたページング条件*実行ページメソッドはツールクラスに記述されます* @param Model*/ @controller public class cmlogcontroller extends defaultcontroller {@requestmapping( "index.do")public modelandview userinto(モデルマップモデル、文字列ユーザー名){namestr = usermame; Model.Addattribute( "username"、namestr); //ページ数long totalcount = logservice.pagecounts(model); //ページ表示ページ= 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(); // Pagination Query loglist = logservice.pageList(model); mv.addobject( "loglist"、loglist); mv.setViewName( "/jsp/log"); MVを返します。 }} 6.メイバティスのいくつかのクエリステートメント
// Pagination Query <Select id = "PageList" parametertype = "map" resultmap = "baseeresultmap"> select ttt。開発中に使用されるSQLインジェクション:sqlのデバッグに便利で、# - >および '%$ {username}%' </if> <type!= type!= '' "> < - >およびtype =#{type、jdbctype = varchar} </if> </where> order by $ {ordername} $ {descasc})tt)ttt <where> "startindex!= null and startIndex!= ''"> rn> $ {startindex!= 'endex!='> '>' enendex! <![cdata [and rn <= $ {endindex}]]> </if> </where> </select> //ページ数<select id = "pagecounts" parametertype = "map" resulttype = "long"> select count(*)from cm_log < '%$ {username}%' </if> </where> </select> 7。フロントデスクページindex.jsp
//ページレイアウトにDIVを追加するだけで//条件としてユーザー名// <jsp:param name = "url" value = "/log/index.do?"/>条件なしの疑問符は存在する必要があります<body> <div align = "right" style = "height =" height = " value = "/log/index.do?username = $ {username}"/> </jsp:include> </div> </body> 8。Page.jsp参照
<%@ページ言語= "java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" <c:set var = "path" value = "$ {pagecontext.request.contextpath}" /> <c:set var = "url" value = "$ {param.url}" /> <c:var = "urlparams" value = "$ {param.urlparams}" />> < value = "$ {path} /$ {url}" /> <tr> <td colspan = "5"> $ {urlparams}合計$ {page.totalcount}記録合計$ {page.totalpage}ページあたりのページ{page.page.everypage} test = "$ {page.hasprepage eq false}"> << homepage <prepage </c:when> <c:aked> <a href = "$ {paturl}&pageaction = first $ {urlparams}"> << homepage </a> <a href = "$ {pathurl}&pageuction" /> <前のページ</a> </c:それ以外の場合は> </c:> ||を選択します<c:chood> <c:test = "$ {page.hasnextpage eq false}">次のページ>最後のページ>最後のページ>> </c:> </c:> <a> <a href = "$ {pathurl}&pageAction =次の$ {urlparams}">次のページ> </a> < href = "$ {paturl}&pageAction = last $ {urlparams}"> last page >> </a> </c:それ以外の場合> </c:選択> <選択= "indexchange" id = "indexchange" onchange = "getCurrentPage(this.value);" end = "$ {page.totalpage}" step = "1"> <option値= "$ {index}" $ {page.currentpage eq index? "selected": "" "}> $ {index} page </option> </c:foreach> </select>ページごとに表示:<select name =" Everypage "id =" everypage "onchange =" seteverypage(this.Value); " value = "$ {pagecount}" $ {page.everypage eq pagecount? "selected": "" "}> $ {pagecount} bar </option> </c:foreach> </select> </td> </td> </tr> <div style = 'display = a class = listlink id =" indexpagehref "href ='# '> </a> document.getElementById( "indexPageHref"); A.href = '$ {paturl}&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 = '$ {paturl}&pageAction = setPage&pageKey ='+everyPage+'$ {urlparams}'; a.setattribute( "onclick"、 ''); A.Click( "return false"); } function sortpage(sortname){var a = document.getElementById( "indexPageHref"); A.href = '$ {paturl}&pageAction = sort&pagekey ='+sortname+'$ {urlparams}'; a.setattribute( "onclick"、 ''); A.Click( "return false"); } </script>上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。