zoukankan      html  css  js  c++  java
  • Servlet+jsp的分页案例

    查询的分页,在web中经常用到。一般,分页要维护的信息很多,我们把这些相关的信息,分装到一个类中,PageBean。具体如下:

    代码:

    复制代码
    package cn.itcast.utils;
    
    import java.util.List;
    
    import cn.itcast.entity.Employee;
    
    /**
     * 封装分页的参数
     * 
     * @author Jie.Yuan
     * 
     */
    public class PageBean<T> {
        private int currentPage = 1; // 当前页, 默认显示第一页
        private int pageCount = 4;   // 每页显示的行数(查询返回的行数), 默认每页显示4行
        private int totalCount;      // 总记录数
        private int totalPage;       // 总页数 = 总记录数 / 每页显示的行数  (+ 1)
        private List<T> pageData;       // 分页查询到的数据
        
        // 返回总页数
        public int getTotalPage() {
            if (totalCount % pageCount == 0) {
                totalPage = totalCount / pageCount;
            } else {
                totalPage = totalCount / pageCount + 1;
            }
            return totalPage;
        }
        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }
        
        public int getCurrentPage() {
            return currentPage;
        }
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
        public int getPageCount() {
            return pageCount;
        }
        public void setPageCount(int pageCount) {
            this.pageCount = pageCount;
        }
        public int getTotalCount() {
            return totalCount;
        }
        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }
        
        public List<T> getPageData() {
            return pageData;
        }
        public void setPageData(List<T> pageData) {
            this.pageData = pageData;
        }
        
        
    
    }
    复制代码

    我们在servlet层实现数据的查询。一般的做法是这样的,我们在servlet中维护一个pageBean的实例,在servlet中调用查询,并把pageBean作为参数传入。当查询结束后,pageBean的参数已经是查询后的记过,servlet再把查询后的结果,也就是封装在pageBean中的信息保存到域中发送到jsp页面。下面是servlet中的内容:

    代码:

    复制代码
    /**
     * 4. 控制层开发
     * @author Jie.Yuan
     *
     */
    public class IndexServlet extends HttpServlet {
        // 创建Service实例
        private IEmployeeService employeeService = new EmployeeService();
        // 跳转资源
        private String uri;
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            
            try {
                //1. 获取“当前页”参数;  (第一次访问当前页为null) 
                String currPage = request.getParameter("currentPage");
                // 判断
                if (currPage == null || "".equals(currPage.trim())){
                    currPage = "1";      // 第一次访问,设置当前页为1;
                }
                // 转换
                int currentPage = Integer.parseInt(currPage);
                
                //2. 创建PageBean对象,设置当前页参数; 传入service方法参数
                PageBean<Employee> pageBean = new PageBean<Employee>();
                pageBean.setCurrentPage(currentPage);
                
                //3. 调用service  
                employeeService.getAll(pageBean);    // 【pageBean已经被dao填充了数据】
                
                //4. 保存pageBean对象,到request域中
                request.setAttribute("pageBean", pageBean);
                
                //5. 跳转 
                uri = "/WEB-INF/list.jsp";
            } catch (Exception e) {
                e.printStackTrace();  // 测试使用
                // 出现错误,跳转到错误页面;给用户友好提示
                uri = "/error/error.jsp";
            }
            request.getRequestDispatcher(uri).forward(request, response);
            
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            this.doGet(request, response);
        }
    
    }
    复制代码

    下面是dao层查询的内容:

    代码:

    复制代码
    /**
     * 2. 数据访问层实现
     * @author Jie.Yuan
     *
     */
    public class EmployeeDao implements IEmployeeDao {
    
        @Override
        public void getAll(PageBean<Employee> pb) {
            
            //2. 查询总记录数;  设置到pb对象中
            int totalCount = this.getTotalCount();
            pb.setTotalCount(totalCount);
            
            /*
             * 问题: jsp页面,如果当前页为首页,再点击上一页报错!
             *              如果当前页为末页,再点下一页显示有问题!
             * 解决:
             *        1. 如果当前页 <= 0;       当前页设置当前页为1;
             *        2. 如果当前页 > 最大页数;  当前页设置为最大页数
             */
            // 判断
            if (pb.getCurrentPage() <=0) {
                pb.setCurrentPage(1);                        // 把当前页设置为1
            } else if (pb.getCurrentPage() > pb.getTotalPage()){
                pb.setCurrentPage(pb.getTotalPage());        // 把当前页设置为最大页数
            }
            
            //1. 获取当前页: 计算查询的起始行、返回的行数
            int currentPage = pb.getCurrentPage();
            int index = (currentPage -1 ) * pb.getPageCount();        // 查询的起始行
            int count = pb.getPageCount();                            // 查询返回的行数
            
            
            //3. 分页查询数据;  把查询到的数据设置到pb对象中
            String sql = "select * from employee limit ?,?";
            
            try {
                // 得到Queryrunner对象
                QueryRunner qr = JdbcUtils.getQueryRuner();
                // 根据当前页,查询当前页数据(一页数据)
                List<Employee> pageData = qr.query(sql, new BeanListHandler<Employee>(Employee.class), index, count);
                // 设置到pb对象中
                pb.setPageData(pageData);
                
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            
        }
    
        @Override
        public int getTotalCount() {
            String sql = "select count(*) from employee";
            try {
                // 创建QueryRunner对象
                QueryRunner qr = JdbcUtils.getQueryRuner();
                // 执行查询, 返回结果的第一行的第一列
                Long count = qr.query(sql, new ScalarHandler<Long>());
                return count.intValue();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    复制代码

    最后jsp页面吧查询的结果,从域中拿出来展示。

    代码:

    复制代码
    <body>
          <table border="1" width="80%" align="center" cellpadding="5" cellspacing="0">
              <tr>
                  <td>序号</td>
                  <td>员工编号</td>
                  <td>员工姓名</td>
              </tr>
              <!-- 迭代数据 -->
              <c:choose>
                  <c:when test="${not empty requestScope.pageBean.pageData}">
                      <c:forEach var="emp" items="${requestScope.pageBean.pageData}" varStatus="vs">
                          <tr>
                              <td>${vs.count }</td>
                              <td>${emp.empId }</td>
                              <td>${emp.empName }</td>
                          </tr>
                      </c:forEach>
                  </c:when>
                  <c:otherwise>
                      <tr>
                          <td colspan="3">对不起,没有你要找的数据</td>
                      </tr>
                  </c:otherwise>
              </c:choose>
              
              <tr>
                  <td colspan="3" align="center">
                      当前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }页     &nbsp;&nbsp;
                      
                      <a href="${pageContext.request.contextPath }/index?currentPage=1">首页</a>
                      <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage-1}">上一页 </a>
                      <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage+1}">下一页 </a>
                      <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.totalPage}">末页</a>
                  </td>
              </tr>
              
          </table>
      </body>
    复制代码
  • 相关阅读:
    iphone:URL initWithString 返回为空
    android:unable to instantiate activity componentinfo
    android:进度条
    android:spinner
    android:DDMS查看Threads
    android:ListView:convertView.setTag()来设置数据
    iphone:使用UIImagePickerController从IPhone照片库或照相机获取图像
    android:ListView中的getView原理
    android 从assets和res中读取文件
    android:menu.xml
  • 原文地址:https://www.cnblogs.com/mlgjb/p/8098290.html
Copyright © 2011-2022 走看看