首页 > 代码库 > mybatis 分页
mybatis 分页
一.首先配置下基础类
1.Dialect.java
package com.labway.portal.page; /** * 类似hibernate的Dialect,但只精简出分页部分 * * @author badqiu */ public class Dialect { public boolean supportsLimit() { return false; } public boolean supportsLimitOffset() { return supportsLimit(); } /** * 将sql变成分页sql语句,直接使用offset,limit的值作为占位符.</br> 源代码为: * getLimitString(sql,offset * ,String.valueOf(offset),limit,String.valueOf(limit)) */ public String getLimitString(String sql, int offset, int limit) { return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit)); } /** * 将sql变成分页sql语句,提供将offset及limit使用占位符(placeholder)替换. * * <pre> * 如mysql * dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回 * select * from user limit :offset,:limit * </pre> * * @return 包含占位符的分页sql */ public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) { throw new UnsupportedOperationException("paged queries not supported"); } } 2.MySql5Dialect.java package com.labway.portal.page; public class MySql5Dialect extends Dialect { protected static final String SQL_END_DELIMITER = ";"; public String getLimitString(String sql, boolean hasOffset) { return MySql5PageHepler.getLimitString(sql, -1, -1); } @Override public String getLimitString(String sql, int offset, int limit) { return MySql5PageHepler.getLimitString(sql, offset, limit); } @Override public boolean supportsLimit() { return true; } } 3.MySql5PageHepler.java package com.labway.portal.page; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MySql5PageHepler { /** * 得到查询总数的sql */ public static String getCountString(String querySelect) { querySelect = getLineSql(querySelect); int orderIndex = getLastOrderInsertPoint(querySelect); int formIndex = getAfterFormInsertPoint(querySelect); String select = querySelect.substring(0, formIndex); // 如果SELECT 中包含 DISTINCT 只能在外层包含COUNT if (select.toLowerCase().indexOf("select distinct") != -1 || querySelect.toLowerCase().indexOf("group by") != -1) { return new StringBuffer(querySelect.length()) .append("select count(1) count from (") .append(querySelect.substring(0, orderIndex)) .append(" ) t").toString(); } else { return new StringBuffer(querySelect.length()) .append("select count(1) count ") .append(querySelect.substring(formIndex, orderIndex)) .toString(); } } /** * 得到最后一个Order By的插入点位置 * * @return 返回最后一个Order By插入点的位置 */ private static int getLastOrderInsertPoint(String querySelect) { int orderIndex = querySelect.toLowerCase().lastIndexOf("order by"); if (orderIndex == -1 || !isBracketCanPartnership(querySelect.substring(orderIndex, querySelect.length()))) { throw new RuntimeException("My SQL 分页必须要有Order by 语句!"); } return orderIndex; } /** * 得到分页的SQL * * @param offset * 偏移量 * @param limit * 位置 * @return 分页SQL */ public static String getLimitString(String querySelect, int offset, int limit) { querySelect = getLineSql(querySelect); String sql = querySelect.replaceAll("[^\\s,]+\\.", "") + " limit " + offset + " ," + limit; return sql; } /** * 将SQL语句变成一条语句,并且每个单词的间隔都是1个空格 * * @param sql * SQL语句 * @return 如果sql是NULL返回空,否则返回转化后的SQL */ private static String getLineSql(String sql) { return sql.replaceAll("[\r\n]", " ").replaceAll("\\s{2,}", " "); } /** * 得到SQL第一个正确的FROM的的插入点 */ private static int getAfterFormInsertPoint(String querySelect) { String regex = "\\s+FROM\\s+"; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(querySelect); while (matcher.find()) { int fromStartIndex = matcher.start(0); String text = querySelect.substring(0, fromStartIndex); if (isBracketCanPartnership(text)) { return fromStartIndex; } } return 0; } /** * 判断括号"()"是否匹配,并不会判断排列顺序是否正确 * * @param text * 要判断的文本 * @return 如果匹配返回TRUE,否则返回FALSE */ private static boolean isBracketCanPartnership(String text) { if (text == null || (getIndexOfCount(text, ‘(‘) != getIndexOfCount(text, ‘)‘))) { return false; } return true; } /** * 得到一个字符在另一个字符串中出现的次数 * * @param text * 文本 * @param ch * 字符 */ private static int getIndexOfCount(String text, char ch) { int count = 0; for (int i = 0; i < text.length(); i++) { count = (text.charAt(i) == ch) ? count + 1 : count; } return count; } } 4.OracleDialect.java package com.labway.portal.page; /** * @author badqiu */ public class OracleDialect extends Dialect { @Override public String getLimitString(String sql, int offset, int limit) { sql = sql.trim(); boolean isForUpdate = false; if (sql.toLowerCase().endsWith(" for update")) { sql = sql.substring(0, sql.length() - 11); isForUpdate = true; } StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); pagingSelect .append("select * from ( select row_.*, rownum rownum_ from ( "); pagingSelect.append(sql); pagingSelect.append(" ) row_ ) where rownum_ > " + offset + " and rownum_ <= " + (offset + limit)); if (isForUpdate) { pagingSelect.append(" for update"); } return pagingSelect.toString(); } } 5.Page.java package com.labway.portal.page; public class Page implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; protected int pageSize = 10; // 每页默认10条数据 protected int currentPage = 1; // 当前页 protected int totalPages = 0; // 总页数 protected int totalRows = 0; // 总数据数 protected int pageStartRow = 0; // 每页的起始行数 protected int pageEndRow = 0; // 每页显示数据的终止行数 protected boolean pagination = false; // 是否分页 boolean hasNextPage = false; // 是否有下一页 boolean hasPreviousPage = false; // 是否有前一页 protected String pagedView; // 用于页面显示 Object obj; // 参数对象与返回对象 // List<Object> resultList; // 返回的结果 // Map<String,Object> param; //查询入参 public Page(int rows, int pageSize) { this.init(rows, pageSize); } public Page() { } /** * 初始化分页参数:需要先设置totalRows * */ public void init(int rows, int pageSize) { this.pageSize = pageSize; this.totalRows = rows; if ((totalRows % pageSize) == 0) { totalPages = totalRows / pageSize; } else { totalPages = totalRows / pageSize + 1; } } public void init(int rows, int pageSize, int currentPage) { this.pageSize = pageSize; this.totalRows = rows; if ((totalRows % pageSize) == 0) { totalPages = totalRows / pageSize; } else { totalPages = totalRows / pageSize + 1; } if (currentPage != 0) gotoPage(currentPage); setPagedView(null); } /** * 计算当前页的取值范围:pageStartRow和pageEndRow * */ private void calculatePage() { if ((currentPage - 1) > 0) { hasPreviousPage = true; } else { hasPreviousPage = false; } if (currentPage >= totalPages) { hasNextPage = false; } else { hasNextPage = true; } if (currentPage * pageSize < totalRows) { // 判断是否为最后一页 pageEndRow = currentPage * pageSize; pageStartRow = pageEndRow - pageSize; } else { pageEndRow = totalRows; pageStartRow = pageSize * (totalPages - 1); } } /** * 直接跳转到指定页数的页面 * * @param page */ public void gotoPage(int page) { currentPage = page; calculatePage(); // debug1(); } public void debug1() { System.out.println("要显示的页面数据已经封装,具体信息如下:"); String debug = "共有数据数:" + totalRows + "共有页数:" + totalPages + "当前页数为:" + currentPage + "是否有前一页:" + hasPreviousPage + "是否有下一页:" + hasNextPage + "开始行数:" + pageStartRow + "终止行数:" + pageEndRow; System.out.println(debug); } // public void setPagedView(String path) { // // StringBuffer sb = new StringBuffer(); // sb.append("<TABLE width=‘100%‘ class=‘content9‘>"); // sb.append("<TBODY>"); // sb.append("<TR>"); // sb.append("<TD align=left width=‘50%‘>"); // sb.append(" "); // // if (hasPreviousPage) { // sb.append("<a href=http://www.mamicode.com/‘" // + path // + "page=1‘><IMG title=‘第一页‘ src=http://www.mamicode.com/images/0.gif‘ border=0>"); // sb.append(" "); // sb.append("<a href=http://www.mamicode.com/‘" // + path // + "page=" // + (currentPage - 1) // + "‘><IMG title=‘上一页‘ src=http://www.mamicode.com/images/1.gif‘ border=0>"); // } else { // sb.append("<IMG title=‘第一页‘ src=http://www.mamicode.com/images/0.gif‘ border=0>"); // sb.append(" "); // sb.append("<IMG title=‘上一页‘ src=http://www.mamicode.com/images/1.gif‘ border=0>"); // } // sb.append(" "); // // if (hasNextPage) { // sb.append("<a href=http://www.mamicode.com/‘" // + path // + "page=" // + (currentPage + 1) // + "‘><IMG title=‘下一页‘ src=http://www.mamicode.com/images/2.gif‘ border=0>"); // sb.append(" "); // sb.append("<a href=http://www.mamicode.com/‘" // + path // + "page=" // + totalPages // + "‘><IMG title=‘最末页‘ src=http://www.mamicode.com/images/3.gif‘ border=0>"); // } else { // sb.append("<IMG title=‘下一页‘ src=http://www.mamicode.com/images/2.gif‘ border=0>"); // sb.append(" "); // sb.append("<IMG title=‘最末页‘ src=http://www.mamicode.com/images/3.gif‘ border=0>"); // } // sb.append("</TD>"); // sb.append("<TD align=right width=‘50%‘>"); // sb.append(" 每页<INPUT type=text size=5 name=pageSize value="http:// + pageSize + " class=‘form‘ style=‘width:30px;‘>"); // sb.append("文档总数: " + totalRows + ", 共" + totalPages + "页, 第" // + currentPage + "页, 转到 "); // sb.append("<INPUT type=text size=5 name=page value="http://www.mamicode.com/ + currentPage">"); // sb.append(" "); // sb.append("<INPUT onclick=‘submit_pagedForm()‘ type=button class=‘button2‘ value=http://www.mamicode.com/‘ GO ‘>"); // sb.append(" "); // sb.append("<INPUT name=totalPages type=hidden value=http://www.mamicode.com/‘" + totalPages // + "‘>"); // sb.append(" "); // sb.append("<INPUT name=totalRows type=hidden value=http://www.mamicode.com/‘" + totalRows // + "‘>"); // sb.append(" "); // // sb.append("</TD>"); // sb.append("</TR>"); // sb.append("</TBODY>"); // sb.append("</TABLE>"); // // sb.append("<script type=\"text/javascript\">\n"); // sb.append("function submit_pagedForm(){\n"); // sb.append(" var page = document.forms[0].page.value;\n"); // sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); // sb.append("var flag = reg.test(page);\n"); // sb.append("if(!flag){\n" + "alert(‘跳转页必须是数字‘);\n" + "return false;}\n"); // sb.append("var pageSize = document.forms[0].pageSize.value;\n"); // sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); // sb.append("var flag = reg.test(pageSize);\n"); // sb.append("if(!flag){alert(‘每页显示数必须是数字‘);\n" + "return false;}\n"); // sb.append("var totalPages = 0;\n"); // sb.append("totalPages = document.forms[0].totalPages.value;\n"); // sb.append("if (parseInt(page) > parseInt(totalPages) || parseInt(page) <1) {page =1;}\n"); // sb.append("document.forms[0].submit();\n"); // sb.append("}\n"); // sb.append("function search_pagedForm(page) {\n"); // sb.append("document.forms[0].page.value = page;\n"); // sb.append("document.forms[0].target=‘_self‘;\n"); // sb.append("document.forms[0].submit();\n"); // sb.append("}\n"); // sb.append("</script>\n"); // pagedView = sb.toString(); // // } public void setPagedView(String form) { String formName = "forms[0]"; if (form != null) { formName = form; } StringBuffer sb = new StringBuffer(); sb.append("<INPUT type=hidden name=fromPage id=fromPage value=http://www.mamicode.com/‘‘/>"); sb.append("<TABLE width=‘100%‘ class=‘content9‘ cellpadding=‘0‘ cellspacing=‘0‘>"); sb.append("<TBODY>"); sb.append("<TR>"); sb.append("<TD align=left width=‘40%‘>"); sb.append(" "); if (hasPreviousPage) { // sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(1);return false;‘>"); sb.append(" "); sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘上一页‘ class=‘button‘ onclick=‘search_pagedForm(" + (currentPage - 1) + ");return false;‘>"); // sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(" // + (currentPage - 1) // + // ");return false;‘><IMG title=‘上一页‘ src=http://www.mamicode.com/images/1.gif‘ border=0>"); } else { sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘首页‘ class=‘button‘ onclick=‘search_pagedForm(1);return false;‘ disabled=‘disabled‘>"); sb.append(" "); sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘上一页‘ class=‘button‘ onclick=‘search_pagedForm(" + (currentPage - 1) + ");return false;‘ disabled=‘disabled‘>"); // sb.append("<IMG title=‘第一页‘ src=http://www.mamicode.com/images/0.gif‘ border=0>"); // sb.append(" "); // sb.append("<IMG title=‘上一页‘ src=http://www.mamicode.com/images/1.gif‘ border=0>"); } sb.append(" "); if (hasNextPage) { sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘下一页‘ class=‘button‘ onclick=‘search_pagedForm(" + (currentPage + 1) + ");return false;‘>"); // sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(" // + (currentPage + 1) // + // ");return false;‘><IMG title=‘下一页‘ src=http://www.mamicode.com/images/2.gif‘ border=0>"); sb.append(" "); sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘末页‘ class=‘button‘ onclick=‘search_pagedForm(" + totalPages + ");return false;‘>"); // sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(" // + totalPages // + // ");return false;‘><IMG title=‘最末页‘ src=http://www.mamicode.com/images/3.gif‘ border=0>"); } else { sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘下一页‘ class=‘button‘ onclick=‘search_pagedForm(" + (currentPage + 1) + ");return false;‘ disabled=‘disabled‘>"); sb.append(" "); sb.append("<input type=‘button‘ value=http://www.mamicode.com/‘末页‘ class=‘button‘ onclick=‘search_pagedForm(" + totalPages + ");return false;‘ disabled=‘disabled‘>"); // sb.append("<IMG title=‘下一页‘ src=http://www.mamicode.com/images/2.gif‘ border=0>"); // sb.append(" "); // sb.append("<IMG title=‘最末页‘ src=http://www.mamicode.com/images/3.gif‘ border=0>"); } sb.append("</TD>"); sb.append("<TD align=right width=‘60%‘>"); sb.append("总数: " + totalRows + ", 共" + totalPages + "页, 第" + currentPage + "页, 转到 "); sb.append("<INPUT type=text size=5 name=page value="http://www.mamicode.com/ + currentPage" class=‘form‘ style=‘width:30px;‘>"); sb.append(" "); sb.append(" 每页<INPUT type=text size=5 name=pageSize value="http://www.mamicode.com/+ pageSize + " class=‘form‘ style=‘width:30px;‘>"); sb.append("<INPUT name=totalPages type=hidden value=http://www.mamicode.com/‘" + totalPages + "‘>"); sb.append(" "); sb.append("<INPUT name=totalRows type=hidden value=http://www.mamicode.com/‘" + totalRows + "‘>"); sb.append(" "); sb.append("<INPUT onclick=‘submit_pagedForm()‘ type=button value=http://www.mamicode.com/‘GO‘ class=‘button2‘>"); sb.append(" "); sb.append("</TD>"); sb.append("</TR>"); sb.append("</TBODY>"); sb.append("</TABLE>"); sb.append("<script type=\"text/javascript\">\n"); sb.append("function submit_pagedForm(){\n"); sb.append(" var page = document." + formName + ".page.value;\n"); sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); sb.append("var flag = reg.test(page);\n"); sb.append("if(!flag){\n" + "alert(‘跳转页必须是数字‘);\n" + "return false;}\n"); sb.append("var pageSize = document." + formName + ".pageSize.value;\n"); sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); sb.append("var flag = reg.test(pageSize);\n"); sb.append("if(!flag){alert(‘每页显示数必须是数字‘);\n" + "return false;}\n"); sb.append("var totalPages = 0;\n"); sb.append("totalPages = document." + formName + ".totalPages.value;\n"); sb.append("if (parseInt(page) > parseInt(totalPages) ) {document." + formName + ".page.value =totalPages;}\n"); sb.append("if(parseInt(page) <1) {document." + formName + ".page.value =1;}\n"); sb.append("document." + formName + ".fromPage.value=http://www.mamicode.com/‘true‘;/n"); sb.append("document." + formName + ".submit();\n"); sb.append("}\n"); sb.append("function search_pagedForm(page) {\n"); sb.append("document." + formName + ".page.value = page;\n"); sb.append("document." + formName + ".target=‘_self‘;\n"); sb.append("document." + formName + ".fromPage.value=http://www.mamicode.com/‘true‘;/n"); sb.append("document." + formName + ".submit();\n"); sb.append("}\n"); sb.append("</script>\n"); pagedView = sb.toString(); } public void setPagedView1() { StringBuffer sb = new StringBuffer(); sb.append("<TABLE width=‘100%‘ class=‘content9‘>"); sb.append("<TBODY>"); sb.append("<TR>"); sb.append("<TD align=left width=‘20%‘>"); sb.append(" "); if (hasPreviousPage) { sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(1);return false;‘>"); sb.append(" "); sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(" + (currentPage - 1) + ");return false;‘><IMG title=‘上一页‘ src=http://www.mamicode.com/‘../images/1.gif‘ border=0>"); } else { sb.append("<IMG title=‘第一页‘ src=http://www.mamicode.com/‘../images/0.gif‘ border=0>"); sb.append(" "); sb.append("<IMG title=‘上一页‘ src=http://www.mamicode.com/‘../images/1.gif‘ border=0>"); } sb.append(" "); if (hasNextPage) { sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(" + (currentPage + 1) + ");return false;‘><IMG title=‘下一页‘ src=http://www.mamicode.com/‘../images/2.gif‘ border=0>"); sb.append(" "); sb.append("<a href=http://www.mamicode.com/‘#‘ onclick=‘search_pagedForm(" + totalPages + ");return false;‘><IMG title=‘最末页‘ src=http://www.mamicode.com/‘../images/3.gif‘ border=0>"); } else { sb.append("<IMG title=‘下一页‘ src=http://www.mamicode.com/‘../images/2.gif‘ border=0>"); sb.append(" "); sb.append("<IMG title=‘最末页‘ src=http://www.mamicode.com/‘../images/3.gif‘ border=0>"); } sb.append("</TD>"); sb.append("<TD align=right width=‘80%‘>"); sb.append("文档总数: " + totalRows + ", 共" + totalPages + "页, 第" + currentPage + "页, 转到 "); sb.append("<INPUT type=text size=5 name=page value="http://www.mamicode.com/ + currentPage" class=‘form‘ style=‘width:30px;‘>"); sb.append(" "); sb.append(" 每页<INPUT type=text size=5 name=pageSize value="http://www.mamicode.com/+ pageSize + " class=‘form‘ style=‘width:30px;‘>"); sb.append("<INPUT name=totalPages type=hidden value=http://www.mamicode.com/‘" + totalPages + "‘>"); sb.append(" "); sb.append("<INPUT name=totalRows type=hidden value=http://www.mamicode.com/‘" + totalRows + "‘>"); sb.append(" "); sb.append("<INPUT onclick=‘submit_pagedForm()‘ type=button value=http://www.mamicode.com/‘ GO ‘ class=‘button2‘>"); sb.append(" "); sb.append("</TD>"); sb.append("</TR>"); sb.append("</TBODY>"); sb.append("</TABLE>"); sb.append("<script type=\"text/javascript\">\n"); sb.append("function submit_pagedForm(){\n"); sb.append(" var page = document.forms[0].page.value;\n"); sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); sb.append("var flag = reg.test(page);\n"); sb.append("if(!flag){\n" + "alert(‘跳转页必须是数字‘);\n" + "return false;}\n"); sb.append("var pageSize = document.forms[0].pageSize.value;\n"); sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); sb.append("var flag = reg.test(pageSize);\n"); sb.append("if(!flag){alert(‘每页显示数必须是数字‘);\n" + "return false;}\n"); sb.append("var totalPages = 0;\n"); sb.append("totalPages = document.forms[0].totalPages.value;\n"); sb.append("if (parseInt(page) > parseInt(totalPages) || parseInt(page) <1) {page =1;}\n"); sb.append("document.forms[0].submit();\n"); sb.append("}\n"); sb.append("function search_pagedForm(page) {\n"); sb.append("document.forms[0].page.value = page;\n"); sb.append("document.forms[0].target=‘_self‘;\n"); sb.append("document.forms[0].submit();\n"); sb.append("}\n"); sb.append("</script>\n"); pagedView = sb.toString(); } /** * 前台分页页面导航的显示 * * @return String */ public void setPagedView1(String path) { StringBuffer sb = new StringBuffer(); sb.append(" "); if (hasPreviousPage) sb.append("<a href=http://www.mamicode.com/"" + path + "page=1\"><img src=http://www.mamicode.com/"../images/houtui.gif\" border=0></a> <a href=http://www.mamicode.com/"" + path + "page=" + (currentPage - 1) + "\"><img src=http://www.mamicode.com/"../images/houtui2.gif\" border=0></a>"); else sb.append("<img src=http://www.mamicode.com/"../images/houtui.gif\" border=0> <img src=http://www.mamicode.com/"../images/houtui2.gif\" border=0>"); sb.append(" "); if (hasNextPage) sb.append("<a href=http://www.mamicode.com/"" + path + "page=" + (currentPage + 1) + "\"><img src=http://www.mamicode.com/"../images/qianjin.gif\" border=0></a> <a href=http://www.mamicode.com/"" + path + "page=" + totalPages + "\"><img src=http://www.mamicode.com/"../images/qianjin2.gif\" border=0></a>"); else sb.append("<img src=http://www.mamicode.com/"../images/qianjin.gif\" border=0> <img src=http://www.mamicode.com/"../images/qianjin2.gif\" border=0>"); sb.append(" "); sb.append("当前页/总页数:"); sb.append(currentPage); sb.append("/"); sb.append(totalPages); sb.append(" "); sb.append("<script type=\"text/javascript\">\n"); sb.append("function submit_pagedForm(){\n"); sb.append(" var page = document.forms[0].page.value;\n"); sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); sb.append("var flag = reg.test(page);\n"); sb.append("if(!flag){\n" + "alert(‘跳转页必须是数字‘);\n" + "return false;}\n"); sb.append("var pageSize = document.forms[0].pageSize.value;\n"); sb.append("var reg=eval(‘/^[0-9]+$/‘);\n"); sb.append("var flag = reg.test(pageSize);\n"); sb.append("if(!flag){alert(‘每页显示数必须是数字‘);\n" + "return false;}\n"); sb.append("var totalPages = 0;\n"); sb.append("totalPages = document.forms[0].totalPages.value;\n"); sb.append("if (parseInt(page) > parseInt(totalPages) || parseInt(page) <1) {page =1;}\n"); sb.append("document.forms[0].submit();\n"); sb.append("}\n"); sb.append("function search_pagedForm(page) {\n"); sb.append("document.forms[0].page.value = page;\n"); sb.append("document.forms[0].target=‘_self‘;\n"); sb.append("document.forms[0].submit();\n"); sb.append("}\n"); sb.append("</script>\n"); pagedView = sb.toString(); } // public void setPagedView(String path) { // // StringBuffer sb = new StringBuffer(); // // sb.append("当前页/总页数:"); // sb.append(currentPage); // sb.append("/"); // sb.append(totalPages); // sb.append(" "); // // if (hasPreviousPage) // sb.append( // "<a href=http://www.mamicode.com/"" // + path // + "page=1\">首页</a> <a href=http://www.mamicode.com/"" // + path // + "page=" // + (currentPage - 1) // + "\">上一页</a>"); // else // sb.append("首页 上一页"); // sb.append("/"); // // if (hasNextPage) // sb.append( // "<a href=http://www.mamicode.com/"" // + path // + "page=" // + (currentPage + 1) // + "\">下一页</a> <a href=http://www.mamicode.com/"" // + path // + "page=" // + totalPages // + "\">尾页</a>"); // else // sb.append("下一页 尾页"); // // pagedView = sb.toString(); // } public String getPagedView() { return pagedView; } /** * @return */ public int getCurrentPage() { return currentPage; } /** * @return */ public boolean isHasNextPage() { return hasNextPage; } /** * @return */ public boolean isHasPreviousPage() { return hasPreviousPage; } /** * @return */ public int getPageEndRow() { return pageEndRow; } /** * @return */ public int getPageSize() { return pageSize; } /** * @return */ public int getPageStartRow() { return pageStartRow; } /** * @return */ public int getTotalPages() { return totalPages; } /** * @return */ public int getTotalRows() { return totalRows; } /** * @param i */ public void setTotalPages(int i) { totalPages = i; } /** * @param i */ public void setCurrentPage(int i) { currentPage = i; } /** * @param b */ public void setHasNextPage(boolean b) { hasNextPage = b; } /** * @param b */ public void setHasPreviousPage(boolean b) { hasPreviousPage = b; } /** * @param i */ public void setPageEndRow(int i) { pageEndRow = i; } /** * @param i */ public void setPageSize(int i) { pageSize = i; } /** * @param i */ public void setPageStartRow(int i) { pageStartRow = i; } /** * @param i */ public void setTotalRows(int i) { totalRows = i; } public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } }
6.PageContext.java
package com.labway.portal.page; public class PageContext extends Page { private static ThreadLocal<PageContext> context = new ThreadLocal<PageContext>(); public static PageContext getContext() { PageContext ci = context.get(); if (ci == null) { ci = new PageContext(); context.set(ci); } return ci; } public static void removeContext() { context.remove(); } protected void initialize() { } } 7.ReflectHelper.java package com.labway.portal.page; import java.lang.reflect.Field; /** * @author Administrator 反射工具 */ public class ReflectHelper { /** * 获取obj对象fieldName的Field * * @param obj * @param fieldName * @return */ public static Field getFieldByFieldName(Object obj, String fieldName) { for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { return superClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { } } return null; } /** * 检查是否含有分页或本来就是分页类 * * @param obj * @param fieldName * @return */ public static Object isPage(Object obj, String fieldName) { if (obj instanceof java.util.Map) { java.util.Map map = (java.util.Map) obj; return map.get(fieldName); } else { for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { return superClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { } } return null; } } /** * 获取obj对象fieldName的属性值 * * @param obj * @param fieldName * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static Object getValueByFieldName(Object obj, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = getFieldByFieldName(obj, fieldName); Object value = null; if (field != null) { if (field.isAccessible()) { value = field.get(obj); } else { field.setAccessible(true); value = field.get(obj); field.setAccessible(false); } } return value; } /** * 设置obj对象fieldName的属性值 * * @param obj * @param fieldName * @param value * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void setValueByFieldName(Object obj, String fieldName, Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (obj instanceof java.util.Map) { java.util.Map map = (java.util.Map) obj; map.put(fieldName, value); } else { Field field = obj.getClass().getDeclaredField(fieldName); if (field.isAccessible()) { field.set(obj, value); } else { field.setAccessible(true); field.set(obj, value); field.setAccessible(false); } } } }
8.PaginationInterceptor.java
package com.labway.portal.page.interceptor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import org.apache.ibatis.builder.xml.dynamic.ForEachSqlNode;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import com.labway.portal.page.Dialect;
import com.labway.portal.page.OracleDialect;
import com.labway.portal.page.Page;
import com.labway.portal.page.PageContext;
import com.labway.portal.page.ReflectHelper;
//只拦截select部分
@Intercepts({ @Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class }) })
public class PaginationInterceptor implements Interceptor {
private final static Log log = LogFactory
.getLog(PaginationInterceptor.class);
Dialect dialect = new OracleDialect();
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation
.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String originalSql = boundSql.getSql().trim();
RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];
Object parameterObject = boundSql.getParameterObject();
if (boundSql == null || boundSql.getSql() == null
|| "".equals(boundSql.getSql())) {
return null;
}
// 分页参数--上下文传参
Page page = null;
PageContext context = PageContext.getContext();
// map传参每次都将currentPage重置,先判读map再判断context
if (parameterObject != null) {
page = (Page) ReflectHelper.isPage(parameterObject, "page");
}
// 分页参数--context参数里的Page传参
if (page == null && context.isPagination() == true) {
page = context;
}
// 后面用到了context的东东
if (page != null && page.isPagination() == true) {
int totalRows = page.getTotalRows();
// 得到总记录数
if (true) {// totalRows == 0
StringBuffer countSql = new StringBuffer(
originalSql.length() + 100);
countSql.append("select count(1) from (").append(originalSql)
.append(") t");
Connection connection = mappedStatement.getConfiguration()
.getEnvironment().getDataSource().getConnection();
PreparedStatement countStmt = connection
.prepareStatement(countSql.toString());
BoundSql countBS = new BoundSql(
mappedStatement.getConfiguration(),
countSql.toString(), boundSql.getParameterMappings(),
parameterObject);
setParameters(countStmt, mappedStatement, countBS,
parameterObject);
ResultSet rs = countStmt.executeQuery();
if (rs.next()) {
totalRows = rs.getInt(1);
}
rs.close();
countStmt.close();
connection.close();
}
// 分页计算
page.init(totalRows, page.getPageSize(), page.getCurrentPage());
if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
rowBounds = new RowBounds(page.getPageSize()
* (page.getCurrentPage() - 1), page.getPageSize());
}
// 分页查询 本地化对象 修改数据库注意修改实现
String pagesql = dialect.getLimitString(originalSql,
rowBounds.getOffset(), rowBounds.getLimit());
invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET,
RowBounds.NO_ROW_LIMIT);
BoundSql newBoundSql = new BoundSql(
mappedStatement.getConfiguration(), pagesql,
boundSql.getParameterMappings(),
boundSql.getParameterObject());
MappedStatement newMs = copyFromMappedStatement(mappedStatement,
new BoundSqlSqlSource(newBoundSql));
invocation.getArgs()[0] = newMs;
page.setPagination(false);
}
return invocation.proceed();
}
public static class BoundSqlSqlSource implements SqlSource {
BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this);
}
public void setProperties(Properties arg0) {
}
/**
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.
* DefaultParameterHandler
*
* @param ps
* @param mappedStatement
* @param boundSql
* @param parameterObject
* @throws SQLException
*/
private void setParameters(PreparedStatement ps,
MappedStatement mappedStatement, BoundSql boundSql,
Object parameterObject) throws SQLException {
ErrorContext.instance().activity("setting parameters")
.object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql
.getParameterMappings();
if (parameterMappings != null) {
Configuration configuration = mappedStatement.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration
.getTypeHandlerRegistry();
MetaObject metaObject = parameterObject == null ? null
: configuration.newMetaObject(parameterObject);
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
PropertyTokenizer prop = new PropertyTokenizer(propertyName);
if (parameterObject == null) {
value = http://www.mamicode.com/null;
} else if (typeHandlerRegistry
.hasTypeHandler(parameterObject.getClass())) {
value = http://www.mamicode.com/parameterObject;
} else if (boundSql.hasAdditionalParameter(propertyName)) {
value = http://www.mamicode.com/boundSql.getAdditionalParameter(propertyName);
} else if (propertyName
.startsWith(ForEachSqlNode.ITEM_PREFIX)
&& boundSql.hasAdditionalParameter(prop.getName())) {
value = http://www.mamicode.com/boundSql.getAdditionalParameter(prop.getName());
if (value != null) {
value = http://www.mamicode.com/configuration.newMetaObject(value)
.getValue(
propertyName.substring(prop
.getName().length()));
}
} else {
value = http://www.mamicode.com/metaObject == null ? null : metaObject
.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
throw new ExecutorException(
"There was no TypeHandler found for parameter "
+ propertyName + " of statement "
+ mappedStatement.getId());
}
typeHandler.setParameter(ps, i + 1, value,
parameterMapping.getJdbcType());
}
}
}
}
private MappedStatement copyFromMappedStatement(MappedStatement ms,
SqlSource newSqlSource) {
Builder builder = new MappedStatement.Builder(ms.getConfiguration(),
ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
builder.keyProperty(ms.getKeyProperty());
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.cache(ms.getCache());
MappedStatement newMs = builder.build();
return newMs;
}
}
二.Action类
/** * 标准物质出库 * @return */ public String selectBzwzchuku() { String bzwzname = request.getParameter("ck.bzwzname"); Map<String, Object> params = new HashMap<String, Object>(); params.put("bzwzname", bzwzname); String curpage = request.getParameter("page"); String pageSize = request.getParameter("pageSize"); String fromPage = request.getParameter("fromPage"); PageContext page = PageContext.getContext(); page.setPagedView("pageForm"); if (null == curpage) { page.setCurrentPage(1); page.setPageSize(20); } else { if (!"true".equals(fromPage)) { curpage = "1"; } page.setCurrentPage(Integer.parseInt(curpage)); page.setPageSize(Integer.parseInt(pageSize)); } page.setPagination(true);// 设置是否分页 List<X_bzwz_chuku> bzwzchukulist = customerService.selectBzwzchuku(params); request.setAttribute("bzwzchukulist", bzwzchukulist); request.setAttribute("page", page.getPagedView()); return "selectbzwzchuku"; }
三.页面
<body> <div id="biaoti" class="tbtitle01"> <b>标准物质出库</b> </div> <div class="space_h_10"></div> <s:form action="CustomerAction_selectBzwzchuku" name="pageForm" method="post"> 标准物质名称:<s:textfield name="ck.bzwzname" ></s:textfield> <s:submit value="http://www.mamicode.com/查询"></s:submit> <table width="100%" border="0" cellpadding="6" cellspacing="0" class="tb_form1"> <tr> <th>序号</th> <th>标准物质名称</th> <th>发放岗位</th> <th>发放数量</th> <th>发放日期</th> <th>发放人</th> <th>领用人</th> </tr> <s:iterator value="http://www.mamicode.com/#request.bzwzchukulist" > <tr> <td><s:property value="http://www.mamicode.com/ckid" /></td> <td><s:property value="http://www.mamicode.com/bzwzname" /></td> <td><s:property value="http://www.mamicode.com/ffposition" /></td> <td><s:property value="http://www.mamicode.com/ffnumber" /></td> <td><s:property value="http://www.mamicode.com/ffdate.substring(0,10)" /></td> <td><s:property value="http://www.mamicode.com/ffman" /></td> <td><s:property value="http://www.mamicode.com/lingyongman" /></td> </tr> </s:iterator> </table> <!-- <input type="button" value="http://www.mamicode.com/出库" id="ck"/> --> ${page } </s:form> </body>
本文出自 “大话程序” 博客,请务必保留此出处http://houqida.blog.51cto.com/8877896/1584698
mybatis 分页