关于JavaWeb的分页查询的实现

思路:

1.首先先对显示信息的页面的对象进行封装,以便后面的调用

2. 控制层(controller)获取查询条件以及当前页码,将参数传递业务逻辑层(service)

3. 业务逻辑层(service)获取条件以及当前页页面, 统计符合条件的数据共计多少条,获取当前页的数据,获取到 封装成page传递控制层(dao).

4. 根据条件统计符合条数数据共计多少条,以及当前页的数据.

后台页面的实现

1.编写关于页面信息的实体类(bean或entity):

  1.1这是对页面展示的一些属性的封装

public class PageTools<T> {
    // 每页显示的条数
    private Integer initSize = 5;
    // 总共有多少条数据
    private Integer countNum;
    // 当前是多少页
    private Integer currentPage;
    // 总共有多少页
    private Integer countPage;
    // 上一页
    private Integer prePage;
    // 下一页
    private Integer nextPage;
    // 页面数据
    private List<T> pageList;
//无参构造
 public PageTools() {
    }
 public PageTools(Integer initSize, Integer countNum, Integer currentPage, List<T> pageList) {
        this.initSize = initSize;
        this.countNum = countNum;
        this.currentPage = currentPage;
        this.pageList = pageList;
        int num = this.countNum / this.initSize; // 1 5 / 5 2 6 / 5
       // 如果总条数除以每页显示的条数等于0 ,则为两个数的商否则商 + 1
        this.countPage = this.countNum % this.initSize == 0 ? num : num + 1;
       // 如果当前页小于等于1 , 前一页就等于1 ,否则 当前页 - 1
        this.prePage = this.currentPage <= 1 ? 1 : this.currentPage - 1;
      // 如果当前页大于等于总页码, 下一页等于总页面 ,否则 当前页 + 1
        this.nextPage = this.currentPage >= this.countPage ? this.countPage : this.currentPage + 1;
    }
  //此方法构造方法的重载
    public PageTools(Integer countNum, Integer currentPage, List<T> pageList) {
        this.countNum = countNum;
        this.currentPage = currentPage;
        this.pageList = pageList;
        int num = this.countNum / this.initSize; // 1 5 / 5 2 6 / 5
        // 如果总条数除以每页显示的条数等于0 ,则为两个数的商否则商 + 1
        this.countPage = this.countNum % this.initSize == 0 ? num : num + 1;
        // 如果当前页小于等于1 , 前一页就等于1 ,否则 当前页 - 1
        this.prePage = this.currentPage <= 1 ? 1 : this.currentPage - 1;
        // 如果当前页大于等于总页码, 下一页等于总页面 ,否则 当前页 + 1
        this.nextPage = this.currentPage >= this.countPage ? this.countPage : this.currentPage + 1;
    }

    @Override
    public String toString() {
        return "Page{" +
                "initSize=" + initSize +
                ", countNum=" + countNum +
                ", currentPage=" + currentPage +
                ", countPage=" + countPage +
                ", prePage=" + prePage +
                ", nextPage=" + nextPage +
                ", pageList=" + pageList +
                '}';
    }

    public Integer getInitSize() {
        return initSize;
    }

    public void setInitSize(Integer initSize) {
        this.initSize = initSize;
    }

    public Integer getCountNum() {
        return countNum;
    }

    public void setCountNum(Integer countNum) {
        this.countNum = countNum;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getCountPage() {
        return countPage;
    }

    public void setCountPage(Integer countPage) {
        this.countPage = countPage;
    }

    public Integer getPrePage() {
        return prePage;
    }

    public void setPrePage(Integer prePage) {
        this.prePage = prePage;
    }

    public Integer getNextPage() {
        return nextPage;
    }

    public void setNextPage(Integer nextPage) {
        this.nextPage = nextPage;
    }

    public List<T> getPageList() {
        return pageList;
    }

    public void setPageList(List<T> pageList) {
        this.pageList = pageList;
    }
}

2.对dao层代码的实现:

(这里的数据库工具采用的是Druid ,

使用方法:

配置文件:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/tcl?useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true
username=root
password=root
# 初始连接数
initialSize=3

编写druid工具类,Dao层可直接调用 

public class Druid {
    public static DataSource getDatasource() {
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        try {
            properties.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataSource dataSource = null;
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;

    }
  public static Connection getconnection() throws SQLException {
        return  getDatasource().getConnection();
  }
}

//分页查询的时候需要用到总记录数等数据因此同时添加对记录数的查询,所以需要实现两个方法
@Override
//此方法是对查询条件和查询结果的处理
    public long getCount(Student student) {//此处用的是sql语句的拼接
      StringBuilder sb=new StringBuilder("select count(*) from student where 1=1");
        String sname = student.getSname();
        if (sname != null && sname.trim() != "") {
            sb.append(" and sname like '%" +sname +"%'");
        }
        String gender = student.getGender();
        if (gender != null && !"-1".equals(gender) && gender.trim() != "") {
            sb.append(" and gender = '" + gender+"'");
        }
        String sql = sb.toString();
        long count = 0;
        try {
            count = qr.query(sql, new ScalarHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;

    }
  @Override
        public List<Student> getPageList(Student student,int start, int num) {
            StringBuilder sb = new StringBuilder("select * from student where 1=1 ");
// 条件的拼接
            conntionSql(student,sb);//调用方法
// 分页参数的拼接
            sb.append(" limit ?,? ");
            String sql = sb.toString();
            System.out.println("sql = " + sql);
            List<Student> pageList = null;
            try {
                pageList = qr.query(sql, new BeanListHandler<>(Student.class),
                        start, num);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return pageList;
        }
//方法的一个封装,上一个getcount()也可以调用此方法
private void conntionSql(Student student, StringBuilder sb) {
        String sname = student.getSname();
        if (sname != null && sname.trim() != "") {
            sb.append(" and sname like '%" +sname +"%'");
        }
        String gender = student.getGender();
        if (gender != null && !"-1".equals(gender) && gender.trim() != "") {
            sb.append(" and gender = '" + gender+"'");
        }
    }

3.对service层代码的实现

public PageTools<Student> getPageInfo(Student student, String currentPage) {
//获取符合条件的总条数
        long count = studentDao.getCount(student);
// 获取页面数据
        int initSzie = 3;
/*
1: 0 (1-1) * initSzie;
2: 3 (2-1) * initSzie
3: 6 (3-1) * initSzie
n: (n-1) * initSzie;
*/
// 当前页的逻辑处理
        int current = 1;
        if(currentPage != null && currentPage.trim() != ""){
            current = Integer.parseInt(currentPage);
        }
        int start = (current - 1) * initSzie;
// 查询获取页面数据
        List<Student> pageList = studentDao.getPageList(student, start, initSzie);
// 将数据封装成page对象
        PageTools<Student> page = new PageTools<>(initSzie, (int) count, current, pageList);
        return page;
    }

4.对控制层代码的实现

 public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String sname = req.getParameter("sname");
        String gender = req.getParameter("gender");
        String currentPage = req.getParameter("currentPage");
// 数据的封装
        Student student = new Student(sname, gender);
        StudentService st = new StudentServiceImpl();
        PageTools<Student> pageInfo = st.getPageInfo(student, currentPage);
// 页面数据的传递
        req.setAttribute("page",pageInfo);
// 条件的回显
        req.setAttribute("student",student);
        req.getRequestDispatcher("queryStu.jsp").forward(req,resp);
    }

 前端页面的部分代码实现:

	<style type="text/css">
		td{
			text-align: center;
			width: 125px;
		}
		.c2{
			margin-left: 40px;
			margin-bottom: 40px;
		}
	</style>
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript">
		$(function () {
// 全选和全不选
			$("#checkAll").click(function () {
				var check = $("#checkAll").prop("checked");
				$("input:checkbox:gt(0)").prop("checked",check);
			})
//批量删除
			$("#batchDel").click(function () {
				var length = $("input:checkbox:gt(0):checked").length;
				console.log(length)
				if(length <= 0){
					alert("请选择要删除的学生!!!")
					return;
				}
				var b = confirm("你确定要删除吗?");
				if (!b){ // 选择取消,就不删除
					return;
				}

// 完成获取需要删除的学生编号,实现删除
				var ids = "";
				$("input:checkbox:gt(0):checked").each(function () {
// 获取每个被选中的复选框的值
					let val = $(this).val();
					ids += "," + val; // ,1,2,3,4
				})
//取出字符串前面的第一个逗号
				var id = ids.substring(1);
				console.log(id);
// 将需要删除的学生编号提交给后台
				location.href = "batchDelete.do?ids=" + id;
			})
		})
	</script>

</head>
<body>
<br/>
<center>
	<form action="queryStu.do" method="get">
		姓名<input name="sname" value="${student.sname}"/>&nbsp;&nbsp;&nbsp;
		性别
		<select name="gender">
			<option value="-1">请选择</option>
			<option value="男" <c:if test="${student.gender ==
'男'}">selected</c:if> >男</option>
			<option value="女" <c:if test="${student.gender ==
'女'}">selected</c:if> >女</option>
		</select>&nbsp;&nbsp;&nbsp;
		<input type="submit" value="查询"/>
	</form>
	<br/>
</center><br/>
<input type="button" id="batchDel" value="批量删除" style="margin-left: 150px"/>
<br/>
<table border="1px" width="80%" align="center" cellpadding="0"
	   cellspacing="0">
	<tr>
		<th><input type="checkbox" id="checkAll" />全选/全不选</th>
		<th>学号</th>
		<th>姓名</th>
		<th>性别</th>
		<th>生日</th>
		<th>爱好</th>
		<th>头像</th>
		<th>操作</th>
	</tr>
	<!-- 遍历学生的信息 -->
	<c:forEach items="${page.pageList}" var="student">
		<tr>
			<td><input type="checkbox" value="${student.sid}" /></td>
			<td>${student.sid}</td>
			<td>${student.sname}</td>
			<td>${student.gender}</td>
			<td>${student.sbir}</td>
			<td>${student.hobby}</td>
				<%-- 后面调整--%>
			<td><img src="/upload/${student.photo}" alt="" width="60px"
					 height="40px"></td>
			<td><a href="updateJsp.do?sid=${student.sid}">修改</a></td>
		</tr>
	</c:forEach>
</table>
<br/><br/>
<center>
	<a href="queryStu.do?
currentPage=1&sname=${student.sname}&gender=${student.gender}" class="c2">首页</a>
	<a href="queryStu.do?
currentPage=${page.prePage}&sname=${student.sname}&gender=${student.gender}"
	   class="c2">上一页</a>
	<a href="queryStu.do?
currentPage=${page.nextPage}&sname=${student.sname}&gender=${student.gender}"
	   class="c2">下一页</a>
	<a href="queryStu.do?
currentPage=${page.countPage}&sname=${student.sname}&gender=${student.gender}"
	   class="c2">尾页</a>
	<span class="c2">当前页码<input size="4" value="${page.currentPage}"/></span>
	<span class="c2">总记录数<input size="4" value="${page.countNum}"/></span>
</center>
</body>


</html>

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值