基于jsp的原生分页查询。

  1. servlet代码
     
    package com.dl.controller;
    
    import com.dl.entity.Student;
    import com.dl.service.StudentService;
    import com.dl.service.impl.StudentServiceImpl;
    import com.dl.utils.PageUtil;
    
    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 java.io.IOException;
    import java.util.List;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:58
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    @WebServlet("/studentByPageServlet")
    public class StudentByPageServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //设置请求的编码
            req.setCharacterEncoding("utf-8");
            //设置响应的编码
            resp.setContentType("text/html;charset=utf-8");
            //获取前端请求的参数
            String no = req.getParameter("pageNo");
            //判断是否为空,如果为空,则,默认显示第一页
            if (no == null){
                no = "1";
            }
            //将 no 转成int类型
            int pageNo = Integer.parseInt(no);
            //定义每页显示的条数,这里规定每页显示3条数据
            int pageSize = 3;
            //调用方法查询数据 -- 分页查询
            StudentService studentService = new StudentServiceImpl();
            List<Student> studentByPage = studentService.getStudentByPage(pageNo, pageSize);
            //计算总记录数  -- 因为这里的BaseDao里面封装的方法不全,所以这里间接的求取总记录数
            List<Student> allStudents = studentService.getAll();
            int size = allStudents.size();
            //创建一个PageUtil对象  -- 目的是为了通过其获取分页的总数量。一共有多少页
            PageUtil pageUtil = new PageUtil();
            //设置总记录数
            pageUtil.setDataCount(size);
            //设置每页显示的条数
            pageUtil.setPageSize(pageSize);
            //通过上面的两步的设置我们可以通过PageUtil对象获得总页数
            int pageCount = pageUtil.getPageCount();
            //将pageCount存入到request域对象中
            req.setAttribute("pageCount",pageCount);
            //将查询到的额分页的数据添加的request域对象中
            req.setAttribute("students",studentByPage);
            //将当前的页码数也存到request域对象中
            req.setAttribute("pageNo",pageNo);
            //转发到指定的页面
            req.getRequestDispatcher("studentByPage.jsp").forward(req,resp);
        }
    }
    
  2. studentDao代码
     
    package com.dl.dao;
    
    import com.dl.entity.Student;
    
    import java.util.List;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:24
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    public interface StudentDao {
        /**
         * 查询所有学生信息
         * @return
         */
        public List<Student> selectAll();
    
        /**
         * 分页查询
         * @param pageNo 当前的页码数
         * @param pageSize 每页显示的条数
         * @return
         */
        public List<Student> selectStudentByPage(int pageNo, int pageSize);
    }
    
  3. studentDaoImpl代码
     
    package com.dl.dao.impl;
    
    import com.dl.dao.StudentDao;
    import com.dl.entity.Student;
    import com.dl.utils.BaseDao;
    
    import java.lang.reflect.InvocationTargetException;
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:24
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    public class StudentDaoImpl extends BaseDao implements StudentDao {
        @Override
        public List<Student> selectAll() {
            //定义sql语句
            String sql = "select * from student";
            //定义一个参数数组,类型Object
            Object[] objects ={};
            try {
                List<Student> students = super.query(sql, objects, Student.class);
                return students;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        public List<Student> selectStudentByPage(int pageNo, int pageSize) {
            //定义sql语句
            String sql = "select * from student limit ?,?";
            //定义参数数组,类型Object。
            Object[] objects ={(pageNo-1)*pageSize,pageSize};
            //执行sql语句
            try {
                List<Student> students = super.query(sql, objects, Student.class);
                return students;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
  4. student实体类
     
    package com.dl.entity;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:19
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    public class Student {
        private int id;
        private String name;
        private int age;
        private String sex;
    
        public Student() {
        }
    
        public Student(int id, String name, int age, String sex) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    }
    
  5. studentService代码
     
    package com.dl.service;
    
    import com.dl.entity.Student;
    
    import java.util.List;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:24
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    public interface StudentService {
        /**
         * 获取全部的学生信息
         * @return
         */
        public List<Student> getAll();
    
        /**
         * 分页获取学生的信息
         * @param pageNo
         * @param pageSize
         * @return
         */
        public List<Student> getStudentByPage(int pageNo, int pageSize);
    }
    
  6. studentServiceImpl代码
     
    package com.dl.service.impl;
    
    import com.dl.dao.StudentDao;
    import com.dl.dao.impl.StudentDaoImpl;
    import com.dl.entity.Student;
    import com.dl.service.StudentService;
    
    import java.util.List;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:25
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    public class StudentServiceImpl implements StudentService {
        private StudentDao studentDao;
        @Override
        public List<Student> getAll() {
            studentDao = new StudentDaoImpl();
            List<Student> students = studentDao.selectAll();
            return students;
        }
    
        @Override
        public List<Student> getStudentByPage(int pageNo, int pageSize) {
            studentDao = new StudentDaoImpl();
            List<Student> students = studentDao.selectStudentByPage(pageNo, pageSize);
            return students;
        }
    }
    
  7. BaseDao代码
     
    package com.dl.utils;
    
    import org.apache.commons.beanutils.BeanUtils;
    
    import java.lang.reflect.InvocationTargetException;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 这个类是对数据库进行增删改查的
     */
    public class BaseDao {
    
        /**
         * 统一的修改方法,处理增删改的
         * @param sql  需要执行的sql语句
         * @param parameters  对应的sql语句的参数,现在弄成数组了
         * @return
         */
        public int update(String sql, Object[] parameters) throws SQLException{
            if (sql == null) {
                throw new SQLException("sql is null");
            }
            //1.获取数据库的连接
            Connection connection = JdbcUtil.getConnection();
            //2.使用对应的sql获取对应预处理的搬运工
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //3.开始处理参数Object[] obj = new Object[]{"宝强", 12, "经纪人"};
            // String sql = "insert into work (name, age, info) values (?, ?, ?)";
            //获取是参数的个数
            int parameterCount = preparedStatement.getParameterMetaData().getParameterCount();//3
            //4.使用预处理的搬运工对象对咱们的sql语句进行赋值操作
            if (parameters != null && parameters.length == parameterCount) {
                for (int i = 1; i <= parameterCount; i++) {
                    preparedStatement.setObject(i, parameters[i -1]);
                }
            }
            //5执行了sql语句
            int i = preparedStatement.executeUpdate();
            //6.关闭资源
            JdbcUtil.close(connection, preparedStatement);
            return i;
    
        }
    
        /**
         *
         * @param sql
         * @param parameters
         * @param cls  这个参数需要带泛型,来约束当前方法中使用的泛型
         *             这个参数还提供了一个非常重要的信息,指定查询数据的类的对象
         * @param <T>
         * @return
         */
        public <T> List<T> query(String sql, Object[] parameters, Class<T> cls) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
           if (sql == null || cls == null) {
               throw new NullPointerException();
           }
           //1.获取数据库连接对象
            Connection connection = JdbcUtil.getConnection();
           //2.使用sql预处理的搬运工
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //3.参数的处理,借助于参数元数据
            int parameterCount = preparedStatement.getParameterMetaData().getParameterCount();
            //4.对sql里面的?进行赋值
            if (parameters != null && parameters.length == parameterCount) {
                for (int i = 1; i <= parameterCount; i++) {
                    preparedStatement.setObject(i, parameters[i - 1]);
                }
            }
            //5.执行查询的sql
            ResultSet resultSet = preparedStatement.executeQuery();
            //6.准备List集合
            List<T> list = new ArrayList<>();
            //7.获取结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //8.获取字段的个数
            int columnCount = metaData.getColumnCount();
            //9.遍历
            while (resultSet.next()) {
                //10创建类对象(来接数据查询出来的数据)Work work = new Work()
                T t = cls.getConstructor(null).newInstance(null);
                for (int i = 1; i <=  columnCount; i++) {
                    //12.获取字段的名字
                    String columnName = metaData.getColumnName(i);//id, name ,age
                    //13.获取对应字段的数据
                    Object value = resultSet.getObject(columnName);
                    //14.使用BeanUtils给指定字段的数据在类对象中给赋值
                    BeanUtils.setProperty(t, columnName, value);
                }
                //15.存到list集合中
                list.add(t);
            }
            JdbcUtil.close(connection, preparedStatement, resultSet);
            //如果list不为空,就返回list, 如果为空就返回null
            return list.size() != 0 ? list : null;
        }
    }
    

     
  8. jdbcUtil代码
     
    package com.dl.utils;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.sql.*;
    import java.util.Properties;
    
    /**
     * 工具类能干嘛?
     * 1.自动完成驱动的加载
     * 2.自动完成必要的数据处理
     * 3.简化getConnection方法,提供给开发者
     * 4.完成统一的close方法
     */
    public class JdbcUtil {
    
        //c3p0的连接池对象,就会加载默认的xml配置文件,配置文件必须写成固定能够c3p0-config.xml
        //存放的目录必须是srcx下面
        private static ComboPooledDataSource pool = new ComboPooledDataSource();
    
        public static Connection getConnection () {
            Connection connection = null;
            try {
                //connection = DriverManager.getConnection(url, user, password);
                connection = pool.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
        /**
         * 关闭数据库连接对象
         */
        //假如statement 是null   resultSet是null
        public static void close(Connection connection) {
            try {
                close(connection, null, null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //resultSet是null
        public static void close(Connection connection, Statement statement) {
            try {
                close(connection, statement, null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                resultSet.close();
            }
        }
    
    }
    

     
  9. PageUtil代码
     
    package com.dl.utils;
    
    /**
     * @公司 DL19121630工作室
     * @作者 代先生
     * @日期 2021/1/12 -- 16:47
     * @微信 D19121630L
     * @温馨提示:原创代码,翻版必究!如需代写,微信联系!
     */
    public class PageUtil {
        private int pageNo;
        private int pageSize;
        private int pageCount;
        private int dataCount;
    
        public PageUtil(int pageNo, int pageSize, int pageCount, int dataCount) {
            this.pageNo = pageNo;
            this.pageSize = pageSize;
            this.pageCount = pageCount;
            this.dataCount = dataCount;
        }
    
        public PageUtil() {
        }
    
        public int getPageNo() {
            return pageNo;
        }
    
        public void setPageNo(int pageNo) {
            this.pageNo = pageNo;
        }
    
        public int getPageSize() {
            return pageSize;
        }
    
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
    
        public int getPageCount() {
            if (dataCount % pageSize ==0){
                pageCount = dataCount / pageSize;
            }else {
                pageCount = dataCount / pageSize + 1;
            }
            return pageCount;
        }
    
        public void setPageCount(int pageCount) {
            this.pageCount = pageCount;
        }
    
        public int getDataCount() {
            return dataCount;
        }
    
        public void setDataCount(int dataCount) {
            this.dataCount = dataCount;
        }
    
    }
    
  10. index.jsp代码
     
    <%--
      Created by IntelliJ IDEA.
      User: 87421
      Date: 2021/1/12
      Time: 12:43
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
        <a href="${pageContext.request.contextPath}/studentByPageServlet">分页效果</a>
        <br>
        <a href="${pageContext.request.contextPath}/studentServlet">不分页的效果</a>
      </body>
    </html>
    
  11. student.jsp代码
     
    <%--
      Created by IntelliJ IDEA.
      User: 87421
      Date: 2021/1/12
      Time: 16:39
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
            </tr>
            <c:forEach var="student" items="${students}">
                <tr>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.age}</td>
                    <td>${student.sex}</td>
                </tr>
            </c:forEach>
        </table>
    
        <br>
        <br>
        <br>
        <a href="${pageContext.request.contextPath}/studentByPageServlet">分页效果</a>
    </body>
    </html>
    
  12. studentByPage.jsp代码
     
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%--
      Created by IntelliJ IDEA.
      User: 87421
      Date: 2021/1/12
      Time: 16:59
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
            </tr>
            <c:forEach var="student" items="${students}">
                <tr>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.age}</td>
                    <td>${student.sex}</td>
                </tr>
            </c:forEach>
            <tr>
                <td colspan="4">
                    <a href="${pageContext.request.contextPath}/studentByPageServlet?pageNo=1">首页</a>
                    <c:if test="${pageNo==1}">
                        <a>上一页</a>
                    </c:if>
                    <c:if test="${pageNo>1}">
                        <a href="${pageContext.request.contextPath}/studentByPageServlet?pageNo=${pageNo-1}">上一页</a>
                    </c:if>
                    <c:if test="${pageNo==pageCount}">
                        <a>下一页</a>
                    </c:if>
                    <c:if test="${pageNo<pageCount}">
                        <a href="${pageContext.request.contextPath}/studentByPageServlet?pageNo=${pageNo+1}">下一页</a>
                    </c:if>
                    <a href="${pageContext.request.contextPath}/studentByPageServlet?pageNo=${pageCount}">尾页</a>
                </td>
            </tr>
        </table>
        <br>
        <br>
        <br>
        <a href="${pageContext.request.contextPath}/studentServlet">不分页的效果</a>
    </body>
    </html>
    
  13. 项目截图
     

  14. 项目所用jar包

  15. 运行截图


     

猜你喜欢

转载自blog.csdn.net/weixin_45634682/article/details/112540437