• Java Web总结十三之二分页


    一、分页代码类结构:

    二、每个类具体代码

    1、DbConfig.properties:

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/mydb3
    user=root
    password=root

    2、IUserDao.java:

    package com.gnnuit.web.fy.dao;
    
    import java.util.List;
    
    import com.gnnuit.web.fy.domain.UserInfo;
    
    public interface IUserDao {
        // 获取每一页的详细信息
        public List<UserInfo> find(int start, int size);
    
        // 获取总记录数
        public int getAllRecordNo();
    }

    3、UserDao.java:

    package com.gnnuit.web.fy.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.gnnuit.web.fy.domain.UserInfo;
    import com.gnnuit.web.fy.util.JdbcUtill;
    
    public class UserDao implements IUserDao {
    
        @Override
        public List<UserInfo> find(int start, int size) {
            List<UserInfo> userInfos = new ArrayList<>();
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            String sql = "select * from user limit ?,?";
            try {
                conn = JdbcUtill.getMySqlConnection();
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, start);
                pstmt.setInt(2, size);
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    UserInfo info = new UserInfo();
                    String id = rs.getString("id");
                    String username = rs.getString("username");
                    String password = rs.getString("password");
                    java.sql.Date birthday = rs.getDate("birthday");
                    int salary = rs.getInt("salary");
    
                    info.setBirthday(birthday);
                    info.setId(Integer.parseInt(id));
                    info.setPassword(password);
                    info.setSalary(salary);
                    info.setUsername(username);
    
                    userInfos.add(info);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return userInfos;
        }
    
        @Override
        public int getAllRecordNo() {
            int sum = 0;
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            String sql = "select count(*) from user";
            try {
                conn = JdbcUtill.getMySqlConnection();
                pstmt = conn.prepareStatement(sql);
                rs = pstmt.executeQuery();
                if(rs.next()){
                    sum=rs.getInt(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JdbcUtill.close(rs);
                JdbcUtill.close(pstmt);
                JdbcUtill.close(conn);
            }
            return sum;
        }
    
    }

    4、Page.java:

    package com.gnnuit.web.fy.domain;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Page {
        private int allRecordNo;// 总记录数
        private int perPageNo = 5;// 每页显示多少条记录
        private int allPageNo;// 总页数
        private int currentPageNo = 1;// 显示的当前页号
        private List<UserInfo> userinfos = new ArrayList<>();// 当前页的所有信息
    
        public Page() {
    
        }
    
        public int getAllRecordNo() {
            return allRecordNo;
        }
    
        public void setAllRecordNo(int allRecordNo) {
            this.allRecordNo = allRecordNo;
            if (allRecordNo % perPageNo == 0) {
                this.allPageNo = allRecordNo / perPageNo;
            } else {
                this.allPageNo = allRecordNo / perPageNo + 1;
            }
        }
    
        public int getPerPageNo() {
            return perPageNo;
        }
    
        public void setPerPageNo(int perPageNo) {
            this.perPageNo = perPageNo;
        }
    
        public int getAllPageNo() {
            return allPageNo;
        }
    
        public void setAllPageNo(int allPageNo) {
            this.allPageNo = allPageNo;
        }
    
        public int getCurrentPageNo() {
            return currentPageNo;
        }
    
        public void setCurrentPageNo(int currentPageNo) {
            this.currentPageNo = currentPageNo;
        }
    
        public List<UserInfo> getUserinfos() {
            return userinfos;
        }
    
        public void setUserinfos(List<UserInfo> userinfos) {
            this.userinfos = userinfos;
        }
    
    }

    5、UserInfo.java:

    package com.gnnuit.web.fy.domain;
    
    import java.util.Date;
    
    public class UserInfo {
        private int id;
        private String username;
        private String password;
        private Date birthday;
        private int salary;
    
        public UserInfo() {
    
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    
        public int getSalary() {
            return salary;
        }
    
        public void setSalary(int salary) {
            this.salary = salary;
        }
    
    }

    6、DaoFactory.java:

    package com.gnnuit.web.fy.factory;
    
    import com.gnnuit.web.fy.dao.IUserDao;
    import com.gnnuit.web.fy.dao.UserDao;
    
    //操作数据库的工厂(单例)
    public class DaoFactory {
        private static DaoFactory daoFactory;
    
        public static DaoFactory getDaoFactory() {
            if (daoFactory == null) {
                daoFactory = new DaoFactory();
            }
            return daoFactory;
        }
    
        private DaoFactory() {
    
        }
    
        public IUserDao getDao() {
            return new UserDao();
        }
    }

    7、UserService.java:

    package com.gnnuit.web.fy.service;
    
    import java.util.List;
    
    import com.gnnuit.web.fy.dao.IUserDao;
    import com.gnnuit.web.fy.domain.Page;
    import com.gnnuit.web.fy.domain.UserInfo;
    import com.gnnuit.web.fy.factory.DaoFactory;
    
    public class UserService {
        private IUserDao dao = DaoFactory.getDaoFactory().getDao();
    
        // 获取当前页的详细信息
        public Page find(int currentPageNo) {
            Page page = new Page();
            page.setCurrentPageNo(currentPageNo);
            int allRecordNo = dao.getAllRecordNo();
            page.setAllRecordNo(allRecordNo);
            int size = page.getPerPageNo();
            int start = (page.getCurrentPageNo() - 1) * size;
            List<UserInfo> userinfos = dao.find(start, size);
            page.setUserinfos(userinfos);
            return page;
        }
    }

    8、JdbcUtill.java

    package com.gnnuit.web.fy.util;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    //操作JDBC的工具类
    public final class JdbcUtill {
        private static String driver;
        private static String url;
        private static String user;
        private static String password;
    
        // 静态代码块:读取配置文件
        static {
            Properties prop = new Properties();
            InputStream is = JdbcUtill.class.getClassLoader().getResourceAsStream(
                    "com/gnnuit/web/fy/config/DbConfig.properties");
            try {
                prop.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");
        }
    
        // 静态代码块:建立数据库的连接
        static {
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 获取MySql数据库的连接
         * 
         * @return Connection对象
         * @throws SQLException
         */
        public static Connection getMySqlConnection() throws SQLException {
            return DriverManager.getConnection(url, user, password);
        }
    
        /**
         * 关闭与数据库的连接
         * 
         * @param rs
         * @throws SQLException
         */
        public static void close(ResultSet rs) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void close(Statement stmt) {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void close(Connection conn) {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    9、UserPageServlet.java:

    package com.gnnuit.web.fy.web;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.gnnuit.web.fy.domain.Page;
    import com.gnnuit.web.fy.service.UserService;
    
    public class UserPageServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String method = request.getParameter("method");
            if (method != null) {
                if("fy".equals(method)){
                    this.fy(request, response);
                }
            } else {
                // 第一次访问没带参数,默认调用分页方法
                this.fy(request, response);
            }
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
        }
    
        private void fy(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String currentPageNo = request.getParameter("currentPageNo");
            UserService userService = new UserService();
            if (currentPageNo == null) {
                // 第一次访问,不带参数,直接访问第一页
                Page page = userService.find(1);
                request.setAttribute("page", page);
                request.getRequestDispatcher("/fy.jsp").forward(request, response);
            } else {
                Page page = userService.find(Integer
                        .parseInt(currentPageNo));
                request.setAttribute("page", page);
                request.getRequestDispatcher("/fy.jsp").forward(request, response);
            }
        }
    
    }

    10、fy.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>My JSP 'fy.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
    <script type="text/javascript">
        function fy(i){
            var uri="/day13/UserPageServlet?method=fy&currentPageNo="+i;
            window.location.href=uri;
        }
    </script>
    
    </head>
    
    <body>
        <table border="1" align="center" width="60%">
            <caption>用户详细信息</caption>
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>生日</th>
                <th>期望薪水</th>
            </tr>
            <c:forEach var="user" items="${page.userinfos }">
                <tr>
                    <td>${user.id }</td>
                    <td>${user.username }</td>
                    <td>${user.password }</td>
                    <td>${user.birthday }</td>
                    <td>${user.salary }</td>
                </tr>
            </c:forEach>
        </table>
        <c:forEach var="i" begin="1" end="${page.allPageNo }" step="1">
            <a href="/day13/UserPageServlet?method=fy&currentPageNo=${i }"
                style="text-decoration: none;">[${i }]&nbsp;</a>
        </c:forEach>
        <select onchange="fy(this.value)">
            <c:forEach var="i" begin="1" end="${page.allPageNo }">
                <option value="${i }" ${i==page.currentPageNo?'selected':'' }>${i }</option>
            </c:forEach>
        </select>
        <br/>
        当前第${page.currentPageNo }页/共${page.allPageNo }页/每页显示${page.perPageNo }条记录
    </body>
    </html>
  • 相关阅读:
    centos7安装nginx的两种方法
    centos7 搭建keepalived+Nginx+tomcat
    Linux下Nginx+Tomcat负载均衡和动静分离配置要点
    Tomcat结合Apache、Nginx实现高性能的web服务器
    centos7安装jdk+tomcat+nginx+mysql
    python3 密码生成器
    如何处理Tomcat日志catalina.out日志文件过大的问题
    Tomcat关闭日志catalina.out
    tomcat 启动项目时出现 ZipException: error in opening zip file
    [科普]MinGW vs MinGW-W64及其它(比较有意思,来自mingw吧)
  • 原文地址:https://www.cnblogs.com/FlySheep/p/3661882.html
Copyright © 2020-2023  润新知