A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 长沙-小知姐姐 黑马粉丝团   /  2019-11-8 16:24  /  1138 人查看  /  0 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 长沙-小知姐姐 于 2019-11-8 16:24 编辑

JSP实现分页

咱们在浏览网页的时候,当一个页面的数据不足以展示完全所有的内容,一般都涉及到分页,下一页的功能该怎么实现呢?首先我们来分析一下:

那么直接上代码:
这里需要备注一下,本次的代码是在对三层优化之后进行操作的,所以我先把数据访问层的重构代码贴出来:

package org.ThreeLayer.DButil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.ThreeLayer.Entity.Student;

public class DButil
{
        public static final String driver = "com.mysql.cj.jdbc.Driver";
        public static final String url = "jdbc:mysql://localhost:3306/zxy?&useSSL=false&serverTimezone=UTF-8&useSSL=false&serverTimezone = GMT";
        public static final String username = "root";
        public static final String password = "zxy170518.";
        public static Connection connection = null;//链接数据库
        public static PreparedStatement pstmt=null;//执行sql语句
        public static ResultSet rs=null;
        
        
        public static Connection getConnection() throws SQLException, ClassNotFoundException
        {
                Class.forName(driver);
                return DriverManager.getConnection(url,username,password);
        }
        
        public static int getTotalCount(String sql)
        {
                int count=0;
                try
                {
                        pstmt=createPrepareStatement(sql, null);
                        rs=pstmt.executeQuery();
                        if(rs.next())
                        {
                                count=rs.getInt(1);
                        }
                }catch(SQLException e)
                {
                        e.printStackTrace();
                }catch(ClassNotFoundException e)
                {
                        e.printStackTrace();
                }catch(Exception e)
                {
                        e.printStackTrace();
                }finally
                {
                        closeAll(connection, pstmt, rs);
                }
                return count;
        }
        
        public static PreparedStatement createPrepareStatement(String sql,Object[] obj) throws ClassNotFoundException, SQLException
        {
                pstmt=getConnection().prepareStatement(sql);
                if(obj!=null)
                {
                        for(int i=0;i<obj.length;i++)
                        {
                                pstmt.setObject(i+1, obj);//进行更新动作
                        }
                }
                return pstmt;
        }
        
        public static boolean UpdateSQL(String sql,Object[] obj)
        {
               try
               {
                        pstmt=createPrepareStatement(sql, obj);
                        int count=pstmt.executeUpdate();
                        if(count>0)
                        {
                                return true;
                        }
                        else
                        {
                                return false;
                        }
                } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return false;
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return false;
                }finally
                {
                        closeAll(connection,pstmt,rs);
                }
        }
        
        
        public static ResultSet FindSQL(String sql,Object[] obj)
        {
                try
                {
                        pstmt=createPrepareStatement(sql, obj);
                        rs=pstmt.executeQuery();
                        return rs;
                }catch(ClassNotFoundException e)
                {
                        e.printStackTrace();
                        return rs;
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return rs;
                }catch(Exception e)
                {
                        e.printStackTrace();
                        return rs;
                }
        }
        
        public static void closeAll(Connection connection,PreparedStatement pstmt,ResultSet rs)
        {
                try
                {
                        if(connection!=null);
                        connection.close();
                        if(pstmt!=null);
                        pstmt.close();
                        if(rs!=null);
                        rs.close();
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }catch(Exception e)
                {
                        e.printStackTrace();
                }
        }
}


基本上就是普通的数据库操作功能,很好懂,就不多解释了;
对于数据访问层的Dao:

public int getTotalCount()//查询数据总数
        {
                String sql="select count(1) from student";
                return DButil.getTotalCount(sql);
        }
        
        public List<Student> findStudentByPage(int currentPage,int pageSize)//currentPage:当前页数;pageSize页面所能容纳的最大数据量
        {
                String sql="select * from student limit ? , ?";
                Object[] obj= {currentPage*pageSize,pageSize};
                List<Student> students=new ArrayList<>();
                ResultSet rs=DButil.FindSQL(sql, obj);
                try {
                        while(rs.next())
                        {
                                Student student=new Student(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4));
                                students.add(student);
                        }
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                return students;
        }

对于业务逻辑层:
Server:

public int getTotalCount()
        {
                return studentdao.getTotalCount();
        }
        
        public List<Student> findStudentByPage(int currentPage,int pageSize)
        {
                return studentdao.findStudentByPage(currentPage, pageSize);
        }

对于视图层的后台代码:
Servlet:

package org.Three.Servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ThreeLayer.Entity.Page_S;
import org.ThreeLayer.Entity.Student;
import org.ThreeLayer.Server.Student_Server;

public class findStudentByPage extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                Student_Server studentS=new Student_Server();
        //        int currentPage=2;
               
                Page_S pag=new Page_S();
               
                String tmp=request.getParameter("currentPage");
                if(tmp==null)//判断是否为第一次进行访问
                {
                        tmp="0";
                }
               
                int sum=studentS.getTotalCount();
                pag.setTotalCount(sum);
               
                int currentPage= Integer.parseInt(tmp);
                pag.setCurrentPage(currentPage);
               
                String tmp2=request.getParameter("choose");
                if(tmp2==null)//默认一页3个内容
                {
                        tmp2="3";
                }
               
                int pageSize=Integer.parseInt(tmp2);
                pag.setPageSize(pageSize);
                List<Student> students =studentS.findStudentByPage(currentPage, pageSize);
                pag.setStudents(students);
                request.setAttribute("pag", pag);
                request.getRequestDispatcher("index.jsp").forward(request, response);
                System.out.print(students);
                System.out.print(sum);
        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
        }

}


还有一个实体类:Page:

package org.ThreeLayer.Entity;

import java.util.List;

public class Page_S {//为了不出现于重名,改了一下
        private int currentPage;
        private int pageSize;//页面大小,即页面数据个数
        private int totalCount;//总数据
        private int totalPage;//总页数
        private List<Student> students;
        public Page_S() {
        }
        public Page_S(int currentPage, int pageSize, int totalCount, int totalPage, List<Student> students) {
                this.currentPage = currentPage;
                this.pageSize = pageSize;
                this.totalCount = totalCount;
                this.totalPage = totalPage;
                this.students = students;
        }
        public int getCurrentPage() {
                return currentPage;
        }
        public void setCurrentPage(int currentPage) {
                this.currentPage = currentPage;
        }
        public int getPageSize() {
                return pageSize;
        }
        public void setPageSize(int pageSize) {
                this.pageSize = pageSize;
                this.totalPage=this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1;
        }
        public int getTotalCount() {
                return totalCount;
        }
        public void setTotalCount(int totalCount) {
                this.totalCount = totalCount;
        }
        public int getTotalPage() {
                return totalPage;
        }
        public void setTotalPage(int totalPage) {
                this.totalPage = totalPage;
        }
        public List<Student> getStudents() {
                return students;
        }
        public void setStudents(List<Student> students) {
                this.students = students;
        }
}


最后贴上index.jsp:

<%@page import="java.util.List"%>
<%@page import="org.ThreeLayer.Entity.Student"%>
<%@page import="org.ThreeLayer.Entity.Page_S"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息管理</title>
</head>
<body>
                <table border=1px>
                        <tr>
                        <th>学号</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>操作</th>
                        </tr>
                        <%
                        Page_S pagg=(Page_S)request.getAttribute("pag");
                        for(Student student:pagg.getStudents())
                        {
                        %>
                        <tr>
                        <th><a href="FindStudentById_Servlet?uid=<%=student.getId()%>"><%=student.getId() %></a></th>
                        <th><%=student.getName() %></th>
                        <th><%=student.getSex() %></th>
                        <th><a href="DeleteStudent_Servlet?uid=<%=student.getId()%>">删除</a></th>
                        </tr>
                        <%
                        }
                        %>
                </table>
                <a href="add.jsp">增加</a>
                <%
                        if(pagg.getCurrentPage()==0)//用户位于首页的时候
                        {
                %>               
                        <a href="findStudentByPage?currentPage=<%=pagg.getCurrentPage()+1%>">下一页</a>
                        <a href="findStudentByPage?currentPage=<%=pagg.getTotalPage()-1%>">尾页</a>
                <%                 
                        }else if(pagg.getCurrentPage()==pagg.getTotalPage()-1)//用户位于尾页的时候
                        {
                %>
                        <a href="findStudentByPage?currentPage=0">首页</a>
                        <a href="findStudentByPage?currentPage=<%=pagg.getCurrentPage()-1%>">上一页</a>
                <%
                        }else//用户位于中间页面的时候
                        {
                %>      <a href="findStudentByPage?currentPage=0">首页</a>
                                <a href="findStudentByPage?currentPage=<%=pagg.getCurrentPage()+1%>">下一页</a>
                                <a href="findStudentByPage?currentPage=<%=pagg.getCurrentPage()-1%>">上一页</a>
                                <a href="findStudentByPage?currentPage=<%=pagg.getTotalPage()-1%>">尾页</a>
                <%
                        }
                %>
               
                <br>
</body>
</html>

看一下效果图:
首先看数据库内容:

然后是首页:

下一页:

最后是尾页:

总的说明一下:
首先对于功能的阐述,第一步计算总的数据量,然后规定默认容量大小为3,最终在jsp代码中加上跟用户进行交互的功能,即让用户选择一页多少内容(由于我写的那个有点bug,就先不贴,等后面自己能完美实现之后,再更新),之后对前端数据进行打包,要思考的是,我们对于这个功能我们所需要的数据有哪些呢?首先,总数据量要吧?然后要存放总的数据内容吧?然后页面大小需要吧?然后用户所在页面的那个页面位置的数要吧?最后一个就是通过总数据量和页面大小计算出来的总页面数也需要吧?所以,一共就需要记录5个属性值,那就打包成一个JavaBean吧,前面代码也贴出来了。最后要提一点,对于如果我第一次进行访问页面的时候,我应该是有一些属性值是为null的,这样是会报空指针异常的,那么就要进行一些小小的处理,哪些呢?比如如果用户第一次进行访问,系统是收不到用户当前所在页面的页面数值的,那么就要判断一下,(此处上代码)如果是第一次进行访问,那么就给与一个默认值0,也就是第一页,那么就处理好了这个小问题了,诸如此类问题还有就是用户在进行选择一页多少内容的时候,也是需要进行赋予一个默认值的,不然也会报空指针。然后对于web.xml文件内容的设置,首页应该设置为实现分页功能的Servlet,因为你每做一次翻页或者首次访问,虽然都是在index.jsp中,但是你需要把每次做完动作之后得到的新的内容进行请求转发,这样才能实现更新,不然程序会报错。
————————————————
原文链接:Link_zx」 https://blog.csdn.net/qq_44705939/article/details/102961378

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马