zoukankan      html  css  js  c++  java
  • 通用分页查询

    项目思路:

    1.页面:

      包括:结果集,分页控件

    2.Servlet

    3.查询Dao:

      (1) 查询总记录数

      (2) 查询每页数据

    4.通用分页Bean

    项目源码:

    AuthorDao.java:

    package com.dao;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.bean.Author;
    import com.db.DB;
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.PreparedStatement;
    
    public class AuthorDao {
        
        //检验用户名或密码是否正确
        public Author CheckLogin(String username,String password) {
            Author author=null;
            DB db=new DB();
            //获取数据库连接对象
            Connection con=(Connection) db.getCon();
            
            //定义sql语句
            String sql="select * from author where username= ? and password= ?";
            
            try {
                PreparedStatement ps=(PreparedStatement) con.prepareStatement(sql);
                //设置用户名和密码和密码作为参数放到sql
                ps.setString(1,username);
                ps.setString(2, password);
                
                ResultSet rs=ps.executeQuery();
                
                //用户名和密码正确,得到用户数据,进行打包
                if(rs.next()) {
                    author=new Author();
                    author.setId(rs.getInt(1));
                    author.setUsername(rs.getString(2));
                    author.setPassword(rs.getString(3));
                    author.setEmail(rs.getString(4));
                    author.setAddress(rs.getString(5));
                    author.setPhone(rs.getString(6));
                    
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            return author;
        }
        
        
        //查询所有用户信息
        public List<Author> selectallauthor(){
            List<Author> authorlist=new ArrayList<Author>();
            DB db=new DB();
            
            //获取数据库连接对象
            Connection con=(Connection) db.getCon();
            String sql="select * from author";
            
            try {
                
                PreparedStatement ps=(PreparedStatement) con.prepareStatement(sql);
                
                ResultSet rs=ps.executeQuery();
                
                //循环遍历获取用户信息
                while(rs.next()) {
                    Author author=new Author();
                    author.setId(rs.getInt(1));
                    author.setUsername(rs.getString(2));
                    author.setPassword(rs.getString(3));
                    author.setEmail(rs.getString(4));
                    author.setAddress(rs.getString(5));
                    author.setPhone(rs.getString(6));
                    
                    authorlist.add(author);
                    //System.out.println("存放成功");
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
            return authorlist;
        }
        
        //查询用户表总记录数(分页查询)
        public int selectallauctorcount() {
            DB db=new DB();
            Connection con=(Connection) db.getCon();
            String sql="select count(*) from author";
            
            try {
                PreparedStatement ps=(PreparedStatement) con.prepareStatement(sql);
                ResultSet rs=ps.executeQuery();
                
                if(rs.next()) {
                    return rs.getInt(1);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return 0;
        }
    
        /*
         * 分页查询用户数据类型
         * padeIndex数据起始索引
         * padeSize每页显示的数据条数
         */
        public List<Author> sellectallauthorPage(int pageIndex,int pageSize){
            List<Author> list=new ArrayList<Author>();
            Author author=new Author();
            DB db=new DB();
            Connection con=(Connection) db.getCon();
            String sql="select * from author limit ?,?";
            try {
                PreparedStatement ps=(PreparedStatement) con.prepareStatement(sql);
                ps.setObject(1,pageIndex);
                ps.setObject(2, pageSize);
                ResultSet rs=ps.executeQuery();//获取结果集
                
                //遍历结果集获取用户的列表信息
                while(rs.next()) {
                    author=new Author();
                    author.setId(rs.getInt(1));
                    author.setUsername(rs.getString(2));
                    author.setPassword(rs.getString(3));
                    author.setEmail(rs.getString(4));
                    author.setAddress(rs.getString(5));
                    author.setPhone(rs.getString(6));
                    
                    list.add(author);
                    
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return list;
        }
        
        //新增用户信息
        public void add(Author author) {
            
            DB db=new DB();
            Connection con=(Connection) db.getCon();
            
            String sql="insert into author values(id,?,?,?,?,?)";
            try {
                PreparedStatement ps=(PreparedStatement) con.prepareStatement(sql);
    
                ps.setObject(1,author.getUsername());
                ps.setObject(2,author.getPassword());
                ps.setObject(3,author.getEmail());
                ps.setObject(4,author.getAddress());
                ps.setObject(5, author.getPhone());
                
                ps.execute();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //删除用户消息
        public void delete(int id) {
            DB db=new DB();
            Connection con=(Connection) db.getCon();
            
            String sql="delete from author where id=?";
            
            try {
                PreparedStatement ps=(PreparedStatement)con.prepareStatement(sql);
                ps.setObject(1,id);
                
                ps.execute();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    AuthorDao

    AuthorListPageServlet.java:

    package com.servlet;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.bean.Author;
    import com.bean.PageBean;
    import com.dao.AuthorDao;
    
    /**
     * Servlet implementation class AuthorListPageServlet
     */
    @WebServlet("/AuthorListPageServlet")
    public class AuthorListPageServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public AuthorListPageServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            AuthorDao dao=new AuthorDao();
            int pageSize=2;
            String strPage=request.getParameter("currentPage");//接受页面传入的页码
            int record=dao.selectallauctorcount();//总记录数
            int currentPage=1;//默认当前页为第一页
            if(strPage!=null) {
                currentPage=Integer.parseInt(strPage);//当前页码
            }
            PageBean<Author> pb=new PageBean<Author>(currentPage,pageSize,record);       
            List<Author> list=dao.sellectallauthorPage(pb.getPageIndex(),pageSize);//查询某一页的结果集
            pb.setList(list);
            
            request.setAttribute("pageBean", pb);
            request.getRequestDispatcher("userlistpage.jsp").forward(request, response);
        
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request, response);
        }
    
    }
    AuthorListPageServlet

    PageBean.java:

    package com.bean;
    
    import java.util.List;
    /*
     * java中的泛型类和泛型集合
     * 通过使用泛型将工具变成通用的
     */
    
    public class PageBean<T> {
        
    
        private int currentPage;//当前页码
        private int pageIndex;//数据起始索引
        private int pageSize;//每页条数
        private int record;//总记录数
        private int totalPage;//总页数
        
        private List<T> list;//每页显示的结果集
        
        /*
         * 构造函数初始化pageIndex和totalPage
         */
        public PageBean(int currentPage,int pageSize,int record) {
            this.currentPage=currentPage;
            this.pageSize=pageSize;
            this.record=record;
            
            //总页数
            if(record%pageSize==0) {
                //整数,没有多余的页
                this.totalPage=record/pageSize;    
            }else {
                //有多余的数据再增加一页
                this.totalPage=record/pageSize+1;
            }
            
            //数据起始索引
            if(currentPage<1) {
                this.currentPage=1;
            }else if(currentPage>this.totalPage) {
                this.currentPage=this.totalPage;
            }
            this.pageIndex=(this.currentPage-1)*this.pageSize;
            
        }
        
        
        public PageBean(int currentPage, int pageIndex, int pageSize, int record, int totalPage, List<T> list) {
            super();
            this.currentPage = currentPage;
            this.pageIndex = pageIndex;
            this.pageSize = pageSize;
            this.record = record;
            this.totalPage = totalPage;
            this.list = list;
        }
        public int getCurrentPage() {
            return currentPage;
        }
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
        public int getPageIndex() {
            return pageIndex;
        }
        public void setPageIndex(int pageIndex) {
            this.pageIndex = pageIndex;
        }
        public int getPageSize() {
            return pageSize;
        }
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
        public int getRecord() {
            return record;
        }
        public void setRecord(int record) {
            this.record = record;
        }
        public int getTotalPage() {
            return totalPage;
        }
        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }
        public List<T> getList() {
            return list;
        }
        public void setList(List<T> list) {
            this.list = list;
        }
        
        
    
    }
    PageBean

    userlistpage.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@page import="com.bean.PageBean" %>
    <%@page import="com.servlet.AuthorListPageServlet" %>
    <%@page import="com.dao.AuthorDao" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>显示用户详细信息</title>
    </head>
    <body>
    
    <table border="1">
        <tr>
            <td>用户名</td>
            <td>邮箱</td>
            <td>地址</td>
            <td>电话</td>        
            <td>操作</td>
        </tr>
         <c:forEach items="${pageBean.list}" var="author">
     
         <tr>
             <td>${author.username }</td>
             <td>${author.email }</td>
             <td>${author.address }</td>
             <td>${author.phone }</td>
             <td><a href="AuthorServlet?op=delete&id=${author.id }">删除</a></td>
         </tr>
     </c:forEach>
    </table>
    <c:if test="${pageBean.record>0 }">
    <div > 
        <a href="AuthorListPageServlet?currentPage=1">首页</a>
        <a href="AuthorListPageServlet?currentPage=${pageBean.currentPage-1 }">上一页</a>
        <a href="AuthorListPageServlet?currentPage=${pageBean.currentPage+1 }">下一页</a>
        <a href="AuthorListPageServlet?currentPage=${pageBean.totalPage }">尾页</a>
    </div>
    </c:if>
    </body>
    </html>
    userlistpage

    项目运行截图:

     遇到的问题:

    1.编译失败,没有在AuthorListPageServlet.java:中使用utf-8

    解决时间:1分钟

    2.显示结果为空

    原因:自己的命名混淆,currentPage传值的时候,名字用错

    解决时间:6分钟

    3.sql语句:中分页查询数据集的sql语句写错 selsect * from author limit ?,?;中忘记关键字limit

    解决时间:1分钟

    注意项:

    1.在AuthorListPageServlet.java:中进行数据封装和传值的时候,应该将PageBean的泛型类进行封装,并闯到前端页面,而不是list容器

    2,在算当前页面需要显示数据集的时候,current需要与total进行对比,若超出范围则相对应的显示首页和尾页

  • 相关阅读:
    安装7-Zip后,鼠标右键菜单出现选项(CRC SHA)
    Windows添加右键菜单【转载】
    基于Visual Studio开发C++/Qt项目的使用笔记
    数组中的重复数字
    zookeeper的通知机制
    zookeeper有几种部署模式? zookeeper 怎么保证主从节点的状态同步?
    什么是springcloud?springcloud断路器的作用是什么?springcloud的核心组件有什么?
    springboot实现热部署的几种方式
    springboot的核心配置文件
    什么是springboot?为什么要用springboot?
  • 原文地址:https://www.cnblogs.com/hhjing/p/12492364.html
Copyright © 2011-2022 走看看