zoukankan      html  css  js  c++  java
  • 通用分页(二)

    通用分页核心思路:
    将上一次查询请求再发一次,只是当前页变了而已。


    首页 1 2 3 4 … 100 末页 跳转

    MySQL分页:select * from 表 limit 3,3

    每页显示记录数      自己设置
    当前页          来自前端
    总页数          总记录数%每页显示记录数==0?总记录数/每页显示记录数:总记录数/每页显示记录数+1
    总记录数         数据库统计count()
    每页起始记录数      =(当前页-1)*每页显示记录数+1

    总共101条记录,每页显示10条
    第一页: 1-10
    第二页: 11-20
    第三页: 21-30

    每页结尾记录数      =当前页*每页显示记录数

    1、通用的查询方法代码实现

    导入jar包

    commons-beanutils-1.8.0.jar
    commons-logging.jar
    jstl-1.2.jar
    mysql-connector-java-5.1.44-bin.jar
    standard-1.1.2.jar

    连接数据库之前查看自己的用户名、密码、数据库名是否正确

    isOracle:false
    isSQLServer:false
    isMysql:true
    数据库连接(关闭)成功
    #mysql
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=UTF-8
    user=root
    pwd=root

    BookServlet.java

    package com.huang.web;
    
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.huang.dao.BookDao;
    import com.huang.entity.Book;
    import com.huang.util.PageBean;
    
    public class BookServlet extends HttpServlet {
    
        private static final long serialVersionUID = 2331970325281408992L;
    
        private BookDao bookDao=new BookDao();
        
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
        
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String bname=req.getParameter("bname");
    //        bname=new String(bname.getBytes("ISO-8859-1"),"UTF-8");
            Book book=new Book();  
            book.setBname(bname);
            
    //        Map<String, String[]> parameterMap=req.getParameterMap();
    //        StringBuffer url=req.getRequestURL();  
            
            
            PageBean pagebean=new PageBean();
             try {
                 pagebean.setRequest(req);
                List<Book> list=this.bookDao.list(book, pagebean);
                req.setAttribute("bookList", list);
                req.setAttribute("pageBean", pagebean);
                req.getRequestDispatcher("/bookList.jsp").forward(req, resp);
            } catch (InstantiationException | IllegalAccessException | SQLException e) {
                e.printStackTrace();
            }
        }
        
    }

    bookList.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
         <%@taglib uri="/huang" prefix="z"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h2>小说目录</h2>
        <br>
        <form action="${pageContext.request.contextPath}/bookServlet.action"
            method="post">
            书名:<input type="text" name="bname"> <input type="submit"
                value="确定">
                <!-- <input type="hidden" name="pagination" value="false">
                <input type="hidden" name="rows" value="20"> -->
        </form>
        <table border="1" width="100%">
            <tr>
                <td>编号</td>
                <td>名称</td>
                <td>价格</td>
            </tr>
            <c:forEach items="${bookList }" var="b">
                <tr>
                    <td>${b.bid }</td>
                    <td>${b.bname }</td>
                    <td>${b.price }</td>
                </tr>
            </c:forEach>
        </table>
    
        <z:page pageBean="${pageBean }"></z:page>
        
    </body>
    </html>

    PageBean.java

    package com.huang.util;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    public class PageBean {
    
        private int page = 1;// 页码
    
        private int rows = 10;// 页大小
    
        private int total = 0;// 总记录数
    
        private boolean pagination = true;// 是否分页
        
        private Map<String, String[]> paMap=new HashMap<>();
        private String url;
        
        public void setRequest(HttpServletRequest req) {
            
            //保存上一次请求所携带的参数
            this.setPaMap(req.getParameterMap());
            this.setUrl(req.getRequestURI().toString());
    //        在jsp页面来控制是否分页
            this.setPagination(req.getParameter("pagination"));
    //        在jsp页面 控制一页展示多少条
            this.setRows(req.getParameter("rows"));
            this.setPage(req.getParameter("page"));
        }
        
        
        public void setPage(String page) {
            this.page=StringUtils.isNotBlank(page) ? Integer.valueOf(page) : this.page;
            
        }
    
    
        public void setPagination(String pagination) {
            this.pagination=StringUtils.isNotBlank(pagination) ? !"false".equals(pagination) : this.pagination;
        }
    
        public void setRows(String rows) {
            this.rows=StringUtils.isNotBlank(rows) ? Integer.valueOf(rows) : this.rows;
        }
    
        public Map<String, String[]> getPaMap() {
            return paMap;
        }
    
        public void setPaMap(Map<String, String[]> paMap) {
            this.paMap = paMap;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public PageBean() {
            super();
        }
    
        public int getPage() {
            return page;
        }
    
        public void setPage(int page) {
            this.page = page;
        }
    
        public int getRows() {
            return rows;
        }
    
        public void setRows(int rows) {
            this.rows = rows;
        }
    
        public int getTotal() {
            return total;
        }
    
        public void setTotal(int total) {
            this.total = total;
        }
    
        public void setTotal(String total) {
            this.total = Integer.parseInt(total);
        }
    
        public boolean isPagination() {
            return pagination;
        }
    
        public void setPagination(boolean pagination) {
            this.pagination = pagination;
        }
    
        /**
         * 获得起始记录的下标
         * 
         * @return
         */
        public int getStartIndex() {
            return (this.page - 1) * this.rows;
        }
    
        @Override
        public String toString() {
            return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
        }
    
        /**
         * 获取最大的页码数
         * @return
         */
        public int getMaxpage() {
            return this.total % this.rows==0 ?  this.total/this.rows :  this.total/this.rows+1;
        }
        
        /**
         * 获取下一页
         * @return
         */
        public int getNextpage() {
            return this.page< this.getMaxpage() ? this.page+1 : this.page;
        }
        
        /**
         * 获取上一页
         */
        public int getPreviousPage() {
            return this.page > 1 ? this.page-1 : this.page;
        }
        
    }

    Web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
      <display-name>T226_pagebean</display-name>
      <filter>
              <filter-name>encodingFiter</filter-name>
              <filter-class>com.huang.util.EncodingFiter</filter-class>
      </filter>
      
      <filter-mapping>
          <filter-name>encodingFiter</filter-name>
          <servlet-name> *.action</servlet-name>
      </filter-mapping>
      
      
      <servlet>
              <servlet-name>bookServlet</servlet-name>
              <servlet-class>com.huang.web.BookServlet</servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name>bookServlet</servlet-name>
          <url-pattern>/bookServlet.action</url-pattern>
      </servlet-mapping>
    </web-app>

    z.tld

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
        
      <description>huang 1.1 core library</description>
      <display-name>huang core</display-name>
      <tlib-version>1.1</tlib-version>
      <short-name>c</short-name>
     <uri>/huang</uri>
        
        <tag>
             <!--库中的标签(类似c:set c:out的定义)-->
            <name>page</name>
            <!-- 是标签运行具体代码,也就是助手类,下面填写的是助手类的全路径名 -->
            <tag-class>com.huang.tag.PageTag</tag-class>
            <body-content>JSP</body-content>
            <attribute>
            <!-- 该标签的属性 -->
            <name>pageBean</name>
            <!-- 该属性是否必填 -->
            <required>true</required>
            <!-- 是否支持表达式 -->
            <rtexprvalue>true</rtexprvalue>
            </attribute>
        </tag> 
          
          
          
    </taglib>

    PageTag.java

    package com.huang.tag;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.JspWriter;
    import javax.servlet.jsp.tagext.BodyTagSupport;
    
    import com.huang.util.PageBean;
    
    public class PageTag extends BodyTagSupport {
    
        private static final long serialVersionUID = -7819663757698266331L;
    
        private PageBean pageBean;
    
        public PageBean getPageBean() {
            return pageBean;
        }
    
        public void setPageBean(PageBean pageBean) {
            this.pageBean = pageBean;
        }
        
        @Override
        public int doStartTag() throws JspException {
            JspWriter out=pageContext.getOut();
            try {
                out.print(toHTML());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return super.doStartTag();
        }
    
        private String toHTML() {
            StringBuilder sb=new StringBuilder();
    //        拼接下一次发送请求所要提交的隐藏的form表单
            sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
            sb.append("<input type='hidden' name='page'>");
            
            Map<String, String[]> paMap=pageBean.getPaMap();
            if(paMap!=null&&paMap.size()>0) {
                Set<Entry<String, String[]>> entrySet=paMap.entrySet();
                for (Entry<String, String[]> entry : entrySet) {
    //                上一次请求可能携带页码name=page的参数,但是该参数在前面已经单独赋值
    //                为什么要单独赋值呢?因为上一次请求是第一页的数据,下一次可能是第二页,
    //                因为这前后请求page对应的值是不一样的,需要单独赋值
                    if("page".equals(entry.getKey())) {
                        for (String val : entry.getValue()) {
                            sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>");
                        }
                    }
                }
            }
            sb.append("</form>");
            
    //        拼接分页条
            sb.append("<div style='text-align: right; font-size: 12px;'>");
            sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxpage()+"页&nbsp;&nbsp;<a");
            sb.append(" href='javascript:gotoPage(1)'>首页</a>&nbsp;&nbsp;<a");
            sb.append(" href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a>&nbsp;&nbsp;<a");
            sb.append("href='javascript:gotoPage("+pageBean.getNextpage()+")'>下一页</a>&nbsp;&nbsp;<a");
            sb.append("href='javascript:gotoPage("+pageBean.getMaxpage()+")'>尾页</a>&nbsp;&nbsp;<input type='text'");
            sb.append("id='skipPage'");
            sb.append("style='text-align: center; font-size: 12px;  50px;'>&nbsp;&nbsp;<a");
            sb.append("href='javascript:skipPage()'>Go</a>");
            sb.append("</div>");
            
    //         拼接分页所需要的js代码
            sb.append("<script type='text/javascript'>");
            sb.append(" function gotoPage(page) {");
            sb.append("        document.getElementById('pageBeanForm').page.value = page;");
            sb.append("        document.getElementById('pageBeanForm').submit();");
            sb.append(" }");
            sb.append(" function skipPage() {");
            sb.append("            var page = document.getElementById('skipPage').value;");
            sb.append("            if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>maxPage){");
            sb.append("                alert('请输入1~N的数字');");
            sb.append("             return;");
            sb.append("             }");
            sb.append("            gotoPage(page);");
            sb.append("     }");
            sb.append("</script>");
            
            
            return sb.toString();
        }
        
    }
  • 相关阅读:
    Java实现蓝桥杯突击战
    Java实现蓝桥杯突击战
    Java实现蓝桥杯勇者斗恶龙
    Java实现蓝桥杯勇者斗恶龙
    利用cmake来搭建开发环境
    cmake总结
    cmake手册详解----转
    Boost::filesystem 使用小笔记
    Boost学习之可移植路径操作--filesystem
    C++ 檔案、資料夾、路徑處理函式庫:boost::filesystem
  • 原文地址:https://www.cnblogs.com/bf6rc9qu/p/11071021.html
Copyright © 2011-2022 走看看