带模糊查询的网页分页技术

内存分页

分页工具类

package com.baojiwenli.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 内存分页
 * @param <T>
 */
@SuppressWarnings("all")
public class PageBean2<T> {
    private int curPageno; //当前页号
    private int totalPagecount; //总页数
    private int totalRows;  //总记录数
    private int rowsPerPage = 2; //每页记录数

    private List<T> data = new ArrayList<>();

    /*
       list表示所有的记录数
       curPage:当前页号

       已知条件
       总记录数
       每页的记录数

    */
    public void pages(List<T> list,String curPage){
        if(list==null||list.size()==0){
            return ;
        }
        //1总记录数
        this.totalRows = list.size();
        try{
            //当前页号
            this.curPageno = Integer.parseInt(curPage);
        }catch (Exception e){
            //如果异常,默认显示第一页,如果传入的curPage 为空,或者传入的是一个字符串
            this.curPageno = 1;

        }

        //2计算总页数, pages = total %perPage? total/perPage:total/perPage+1;
        totalPagecount = totalRows%rowsPerPage==0?totalRows/rowsPerPage:totalRows/rowsPerPage+1;

        //再次修正对当前页号 进行判断当前页数的取值范围是否合理,并修正
        if(curPageno<=0){
            curPageno = 1;
        }if(curPageno>totalPagecount){
            curPageno = totalPagecount;
        }
        //给每页先固定记录条数
        //4数据,获取每页的开始记录数
        int fromIndex= (curPageno-1)*rowsPerPage;
        int toIndex = fromIndex+rowsPerPage;
        //修正
        if(toIndex > totalRows){
            toIndex = totalRows;

        }

        //5在list拿到的结果集里重新截取
        this.data = list.subList(fromIndex,toIndex);
    }

    public int getCurPageno() {
        return curPageno;
    }

    public void setCurPageno(int curPageno) {
        this.curPageno = curPageno;
    }

    public int getTotalPagecount() {
        return totalPagecount;
    }

    public void setTotalPagecount(int totalPagecount) {
        this.totalPagecount = totalPagecount;
    }

    public int getTotalRows() {
        return totalRows;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    public int getRowsPerPage() {
        return rowsPerPage;
    }

    public void setRowsPerPage(int rowsPerPage) {
        this.rowsPerPage = rowsPerPage;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }
}

控制层

package com.baojiwenli.controller;

import com.baojiwenli.entity.Student;
import com.baojiwenli.service.StudentService;
import com.baojiwenli.utils.*;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/score_student")
public class StudentServlet extends BaseDaoServlet {
    private StudentService service = new StudentService();

    /**
     * 判断session
     * @param request
     * @param response
     * @throws IOException
     */
    public static void session(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取Session
        HttpSession session = request.getSession(false);
        if (session == null||session.getAttribute("loginmethod") == null) {
            request.setAttribute("msg", "非法访问!");
            String context = request.getContextPath();
            System.out.println("列表路径"+context);
            // 非方法的访问
            request.getRequestDispatcher( "login.jsp").forward(request, response);
            return;
        }
    }
    /*
    列表
     */
    public void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=============列表============");

        //来判断session是否为空的情况

        HttpSession session = request.getSession(false);
        if (session == null||session.getAttribute("loginmethod") == null) {
            request.setAttribute("msg", "非法访问!");
            String context = request.getContextPath();
            System.out.println("列表路径"+context);
            // 非方法的访问
            request.getRequestDispatcher( "login.jsp").forward(request, response);
            return;
        }

        String method = (String) session.getAttribute("loginmethod");
        if(method.equals("66")) {

            //获取前端模糊查询的数据
            Student student = MyBeanUtils1.requestToBean(Student.class,request);

            //内存分页
            //获取当前页号,从前端获取,第一次获取的时候肯定是null值
            List<Student> list = service.queryAll(student);
            PageBean2<Student> pageBean2 = new PageBean2<>();
            String curPage = request.getParameter("curPage");
            System.out.println("当前页:"+curPage);
            pageBean2.pages(list,curPage);
            request.setAttribute("pageBean",pageBean2);

            // 将查询数据库的信息存放到request对象,目的页面(新闻列表页面)通过转发获取到
//            request.setAttribute("list", list);
            // 转发到newslist.jsp
            request.getRequestDispatcher("teachers/listStudent.jsp").forward(request, response);

        }else if(method.equals("11")) {
            Student stu = (Student) session.getAttribute("frontstudent");
            Student student = service.query(stu);

            request.setAttribute("student", student);

            // 转发到studentscore.jsp
            request.getRequestDispatcher("students/studentScore.jsp").forward(request, response);
        }
    }
    

前端页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>

    <script src="${pageContext.request.contextPath}/ckeditor/ckeditor.js"></script>
    <meta charset="UTF-8">
    <title>学生成绩单</title>
    <style type="text/css">
        #header {
            width: 500px;
            margin: 0 auto;
            text-align: center
        }

        td, th, form {
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        function go(pageNo) {
            // alert(pageNo);
            myForm.curPage.value = pageNo;
            myForm.submit();
        }
    </script>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // alert(44444);
            $("[name=all]").click(function () {
                $("[name=id]").prop("checked", $(this).prop("checked"));
            });
            $("[value=全部删除]").click(function () {
                alert("全部删除!");
                idform.submit();
            });
        });
    </script>
</head>
<body>
<div id="header">
    <a href="teachers/addStudent.jsp">添加学生信息</a>

    <c:if test="${empty sessionScope.adminteacher}">
        <a href="${pageContext.request.contextPath}/login.jsp">去登录</a>
    </c:if>
    <c:if test="${not empty sessionScope.adminteacher}">
        教师页面欢迎您,${adminteacher.name }   <a href="teacher?action=logout">注销</a>
    </c:if>
</div>
<hr>
<div>
    <input style="float:right; margin-right: 150px" type="button" value="全部删除">
    <form name="myForm" action="score_student?action=list" method="post">
        <input type="hidden" name="curPage">
        学生姓名关键字:<input name="name" value="${param.name}">
        学生院系: <input name="dept" value="${param.dept}">
        <input type="submit" value="搜索">
    </form>

</div>
<hr>
<form name="idform" action="score_student?action=deleteall" method="post">
    <table id="tab" align="center" width="80%" border="1"
           style="border-collapse: collapse;">
        <thead>
        <tr bgcolor="#acacac">
            <th width="8%"><input type="checkbox" name="all">全部</th>
            <th width="15%">学生姓名</th>
            <th>学生院系</th>
            <th>院系主任</th>
            <th>专业课</th>
            <th>成绩</th>
            <th>学生图像</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- varStatus="st" 取下标 通过下标隔行换色-->
        <c:forEach items="${pageBean.data}" var="stu" varStatus="st">
            <tr bgcolor="${st.count%2==0?'#EEEE11':''}">
                <td><input type="checkbox" name="id" value="${stu.stuid}"></td>
                <td>${stu.name }</td>
                <td>${stu.dept}</td>
                <td>${stu.deptteacher}</td>
                <td>${stu.course}</td>
                <td>${stu.score}</td>
                <td><img width="120" src="upload/${stu.photo}">
                    <c:if test="${not empty stu.photo}">
                        <a  href="score_student?action=download&filename=${stu.photo}">下载图片</a>
                    </c:if>
                </td>
                <td><a onclick="return confirm('你确定要删除此记录吗?')"
                       href="score_student?action=delete&stuid=${stu.stuid}&photo=${stu.photo}">删除</a>|
                    <a href="score_student?action=queryupdate&stuid=${stu.stuid}">修改</a>
                </td>


            </tr>
        </c:forEach>
        <c:if test="${empty pageBean.data}">
            <tr>
                <th colspan="8">没有记录</th>
            </tr>
        </c:if>
        </tbody>
        <tfoot>
        <tr>
            <th colspan="8">
                当前页${pageBean.curPageno}/${pageBean.totalPagecount} &nbsp;

                <a href="#" onclick="go(1)">首页</a> &nbsp;
                <a href="#" onclick="go(${pageBean.curPageno-1})">上一页</a> &nbsp;
                <a href="#" onclick="go(${pageBean.curPageno+1})">下一页</a> &nbsp;
                <a href="#" onclick="go(${pageBean.totalPagecount})">尾页</a>&nbsp;
                总记录数:${pageBean.totalRows}
                <select name="curPage" onchange="go(this.value)">
                    <c:forEach begin="1" end="${pageBean.totalPagecount}" var="cc">
                        <c:if test="${cc==pageBean.curPageno}">
                            <option selected="selected">${cc }</option>
                        </c:if>
                        <c:if test="${cc!=pageBean.curPageno}">
                            <option>${cc }</option>
                        </c:if>
                    </c:forEach>
                </select>
            </th>
        </tr>
        </tfoot>
    </table>
</form>
</body>
</html>

页面效果
在这里插入图片描述

数据库分页

分页工具类

package com.baojiwenli.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 分页组件:数据库端分页 当前页 总页数 总记录数 每页显示的记录数
 *
 * 当前页显示记录
 */
public class PageBean<T> {
	private int curPageno; // 当前页号
	private int totalPagecount; // 总页数
	private long totalRows; // 总记录数
	private int rowsPerPage = 3; // 每页的记录数
	private int startRow = 0;
	private long endRow = 0;
	private List<T> data = new ArrayList<T>();

	public PageBean() {}

	public void setCurPageno(int curPageno) {
		this.curPageno = curPageno;
	}

	public int getTotalPagecount() {
		return totalPagecount;
	}

	public void setTotalPagecount(int totalPagecount) {
		this.totalPagecount = totalPagecount;
	}

	public void setEndRow(long endRow) {
		this.endRow = endRow;
	}

	//封装当前页号和总记录数
	public PageBean(String curPage,long totalRows){
		this.setTotalRows(totalRows);
		this.setCurPageno(curPage);
	}
	public int getCurPageno() {
		return curPageno;
	}

	public int getStartRow() {
		return startRow;
	}

	public void setStartRow(int startRow) {
		this.startRow = startRow;
	}

	public long getEndRow() {
		return endRow;
	}

	public void setEndRow(int endRow) {
		this.endRow = endRow;
	}

	//设置当前页号:对当前页进行正确判断
	public void setCurPageno(String curPageno) {
		if(Objects.equals(curPageno,null)){
			this.curPageno = 1;
		}else{
			this.curPageno = Integer.parseInt(curPageno);
		}

		try {
			if (this.curPageno <= 0) {
				this.curPageno = 1;
			}
		} catch (Exception e) {
			this.curPageno = 1;
		}
		// 修正 当前页号
		if (this.curPageno <= 0) {
			this.curPageno = 1;
		}
		// 当前页超出总页数范围时
		if (this.curPageno > totalPagecount) {
			this.curPageno = totalPagecount;
		}

		//计算开始位置的记录数号
		//数据  截取    rowsPerPage
		System.out.println("curpage:"+this.curPageno);
		this.startRow = (this.curPageno-1)*rowsPerPage;
		//计算结束位置的记录数号
		this.endRow = startRow + rowsPerPage;
		System.out.println("start:"+this.startRow);
		System.out.println("end:"+this.endRow);

		//修正
		if(endRow > totalRows) {
			endRow = totalRows;
		}
	}

	public int getTotalPageCount() {
		return totalPagecount;
	}

	public void setTotalPageCount(int totalPageCount) {
		this.totalPagecount = totalPageCount;
	}

	public long getTotalRows() {
		return totalRows;
	}
	/**
	 *	 设置总记录数 同时计算总页数
	 */
	public void setTotalRows(long totalRows) {
		this.totalRows = totalRows;
		// 计算总页数 pages = total/perPage; 100 5----100/5=20 101 5 ----21
		if (totalRows % rowsPerPage == 0) {
			totalPagecount = (int) (totalRows / rowsPerPage);
		} else {
			totalPagecount = (int) (totalRows / rowsPerPage + 1);
		}
	}

	public int getRowsPerPage() {
		return rowsPerPage;
	}

	public void setRowsPerPage(int rowsPerPage) {
		this.rowsPerPage = rowsPerPage;
	}

	public List<T> getData() {
		return data;
	}

	public void setData(List<T> data) {
		this.data = data;
	}

}

dao 层

package com.baojiwenli.dao;

import com.baojiwenli.entity.Student;
import com.baojiwenli.utils.ConnectionUtil;
import com.baojiwenli.utils.PageBean;
import com.baojiwenli.utils.PageBeanSQL;
import com.wdzl.dao.BaseDao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 学生持久层
 */
public class StudentDao extends BaseDao {
    /**
     * 带搜索的sql分页:需要 传入对象  当前页
     */
    public PageBean<Student> queryAll(Student student, String curPage) {
        String sql = "select stuid,name,dept,deptteacher,course,score,photo"
                + " from student_score where 1=1";
        String cql = "select count(*) "
                + " from student_score where 1=1";
        String name = null;
        String dept = null;
        //记录条件查询总记录数
        //记录条件查询
        List<Object> list = new ArrayList<>();
        if (student != null) {
            name = student.getName();
            dept = student.getDept();
            System.out.println("name:" + name);
            System.out.println("dept:" + dept);
            if (name != null && !name.equals("")) {
                sql += " and name like ?";
                cql += " and name like ?";
                list.add("%" + name + "%");
            }
            if (dept != null && !dept.equals("")) {
                sql += " and dept like ?";
                cql += " and dept like ?";
                list.add("%" + dept + "%");
            }
        }

        //sql语句分页排序拼接
        sql += " order by score desc";
        sql += " limit ?,?";//数据库分页

        //分页组件
        //1.总记录数
        int count = getCount(cql, list.toArray());

        //2.通过构造方法给工具类进行封装数据:当前页  总页数  每页条数  总记录数
        PageBean<Student> pageBean = new PageBean<Student>(curPage, count);

        //开始位置  --startRow =--(curPage-1)*rowsPerPage
        //每页开始位置
        list.add(pageBean.getStartRow());
        //每页显示记录数
        list.add(pageBean.getRowsPerPage());
        List<Student> list1 = super.query(sql, Student.class, list.toArray());
        pageBean.setData(list1);
        //这步的时候已经获取的数据---总记录数  当前页  总页数  条数每页  显示当前页数据记录
        return pageBean;
    }

    /**
     * String sql = select title,content from news where 1=1  and title='sss';
     * String cql = "select count(*)"+sql.subString(sql.lastIndexOf(" from "));
     * <p>
     * select count(*) from news where 1=1  and title='sss'
     */
    public int getCount(String sql,Object[] param) {
		String xxx = "select count(*) from student_score ";

        Connection conn = ConnectionUtil.getConnection();

        int count = 0;
        try {
            pst = conn.prepareStatement(xxx);
            rst = pst.executeQuery();

            //给占位符赋值
            for (int i = 0; i < param.length; i++) {
                pst.setObject(i + 1, param[i]);
            }

            if (rst.next()) {
                count = rst.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    public static void main(String[] args) {
        StudentDao dao = new StudentDao();
        List<Object> list = new ArrayList<>();

		int count = dao.getCount(null,list.toArray());
		System.out.println("===="+count);
    }
}

控制层

package com.baojiwenli.controller;

import com.baojiwenli.entity.Student;
import com.baojiwenli.service.StudentService;
import com.baojiwenli.utils.*;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/score_student")
public class StudentServlet extends BaseDaoServlet {
    private StudentService service = new StudentService();

    /**
     * 判断session
     * @param request
     * @param response
     * @throws IOException
     */
    public static void session(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取Session
        HttpSession session = request.getSession(false);
        if (session == null||session.getAttribute("loginmethod") == null) {
            request.setAttribute("msg", "非法访问!");
            String context = request.getContextPath();
            System.out.println("列表路径"+context);
            // 非方法的访问
            request.getRequestDispatcher( "login.jsp").forward(request, response);
            return;
        }
    }
    /*
    列表
     */
    public void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=============列表============");

        //来判断session是否为空的情况

        HttpSession session = request.getSession(false);
        if (session == null||session.getAttribute("loginmethod") == null) {
            request.setAttribute("msg", "非法访问!");
            String context = request.getContextPath();
            System.out.println("列表路径"+context);
            // 非方法的访问
            request.getRequestDispatcher( "login.jsp").forward(request, response);
            return;
        }

        String method = (String) session.getAttribute("loginmethod");
        if(method.equals("66")) {

            //获取前端模糊查询的数据
            Student student = MyBeanUtils1.requestToBean(Student.class,request);

            
            //数据库分页
            //获取下页页号
            String curPage = request.getParameter("curPage");
            System.out.println("当前页:"+curPage);
            PageBean<Student> pageBean = service.queryAll(student,curPage);  //带条件
            request.setAttribute("pageBean",pageBean);

            // 将查询数据库的信息存放到request对象,目的页面(新闻列表页面)通过转发获取到
//            request.setAttribute("list", list);
            // 转发到newslist.jsp
            request.getRequestDispatcher("teachers/listStudent.jsp").forward(request, response);

        }else if(method.equals("11")) {
            Student stu = (Student) session.getAttribute("frontstudent");
            Student student = service.query(stu);

            request.setAttribute("student", student);

            // 转发到studentscore.jsp
            request.getRequestDispatcher("students/studentScore.jsp").forward(request, response);
        }
    }
    

前端页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>

    <script src="${pageContext.request.contextPath}/ckeditor/ckeditor.js"></script>
    <meta charset="UTF-8">
    <title>学生成绩单</title>
    <style type="text/css">
        #header {
            width: 500px;
            margin: 0 auto;
            text-align: center
        }

        td, th, form {
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        function go(pageNo) {
            // alert(pageNo);
            myForm.curPage.value = pageNo;
            myForm.submit();
        }
    </script>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // alert(44444);
            $("[name=all]").click(function () {
                $("[name=id]").prop("checked", $(this).prop("checked"));
            });
            $("[value=全部删除]").click(function () {
                alert("全部删除!");
                idform.submit();
            });
        });
    </script>
</head>
<body>
<div id="header">
    <a href="teachers/addStudent.jsp">添加学生信息</a>

    <c:if test="${empty sessionScope.adminteacher}">
        <a href="${pageContext.request.contextPath}/login.jsp">去登录</a>
    </c:if>
    <c:if test="${not empty sessionScope.adminteacher}">
        教师页面欢迎您,${adminteacher.name }   <a href="teacher?action=logout">注销</a>
    </c:if>
</div>
<hr>
<div>
    <input style="float:right; margin-right: 150px" type="button" value="全部删除">
    <form name="myForm" action="score_student?action=list" method="post">
        <input type="hidden" name="curPage">
        学生姓名关键字:<input name="name" value="${param.name}">
        学生院系: <input name="dept" value="${param.dept}">
        <input type="submit" value="搜索">
    </form>

</div>
<hr>
<form name="idform" action="score_student?action=deleteall" method="post">
    <table id="tab" align="center" width="80%" border="1"
           style="border-collapse: collapse;">
        <thead>
        <tr bgcolor="#acacac">
            <th width="8%"><input type="checkbox" name="all">全部</th>
            <th width="15%">学生姓名</th>
            <th>学生院系</th>
            <th>院系主任</th>
            <th>专业课</th>
            <th>成绩</th>
            <th>学生图像</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- varStatus="st" 取下标 通过下标隔行换色-->
        <c:forEach items="${pageBean.data}" var="stu" varStatus="st">
            <tr bgcolor="${st.count%2==0?'#EEEE11':''}">
                <td><input type="checkbox" name="id" value="${stu.stuid}"></td>
                <td>${stu.name }</td>
                <td>${stu.dept}</td>
                <td>${stu.deptteacher}</td>
                <td>${stu.course}</td>
                <td>${stu.score}</td>
                <td><img width="120" src="upload/${stu.photo}">
                    <c:if test="${not empty stu.photo}">
                        <a  href="score_student?action=download&filename=${stu.photo}">下载图片</a>
                    </c:if>
                </td>
                <td><a onclick="return confirm('你确定要删除此记录吗?')"
                       href="score_student?action=delete&stuid=${stu.stuid}&photo=${stu.photo}">删除</a>|
                    <a href="score_student?action=queryupdate&stuid=${stu.stuid}">修改</a>
                </td>


            </tr>
        </c:forEach>
        <c:if test="${empty pageBean.data}">
            <tr>
                <th colspan="8">没有记录</th>
            </tr>
        </c:if>
        </tbody>
        <tfoot>
        <tr>
            <th colspan="8">
                当前页${pageBean.curPageno}/${pageBean.totalPagecount} &nbsp;

                <a href="#" onclick="go(1)">首页</a> &nbsp;
                <a href="#" onclick="go(${pageBean.curPageno-1})">上一页</a> &nbsp;
                <a href="#" onclick="go(${pageBean.curPageno+1})">下一页</a> &nbsp;
                <a href="#" onclick="go(${pageBean.totalPagecount})">尾页</a>&nbsp;
                总记录数:${pageBean.totalRows}
                <select name="curPage" onchange="go(this.value)">
                    <c:forEach begin="1" end="${pageBean.totalPagecount}" var="cc">
                        <c:if test="${cc==pageBean.curPageno}">
                            <option selected="selected">${cc }</option>
                        </c:if>
                        <c:if test="${cc!=pageBean.curPageno}">
                            <option>${cc }</option>
                        </c:if>
                    </c:forEach>
                </select>
            </th>
        </tr>
        </tfoot>
    </table>
</form>
</body>
</html>

页面效果
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章