JAVA基础编程110——分页封装

一、准备工作

1、jar包:

在这里插入图片描述

  • spring依赖包
    spring-tx-5.0.0.RELEASE.jar
    spring-jdbc-5.0.0.RELEASE.jar
    spring-core-5.0.0.RELEASE.jar
    spring-beans-5.0.0.RELEASE.jar
    commons-logging-1.2.jar

  • mysql驱动包及连接池依赖
    mysql-connector-java-5.1.37-bin.jar
    druid-1.0.9.jar

  • 请求参数封装包
    commons-beanutils-1.8.0.jar

  • jsp依赖包
    javax.servlet.jsp.jstl.jar
    jstl-impl.jar

2、js依赖

在这里插入图片描述

  • jquery框架依赖文件
  • bootstap框架依赖文件
二、代码实现

1、jdbc配置

2、实体类封装

package com.mollen.domain;

/**
 * @ClassName: User
 * @Auther: Mollen
 * @CreateTime: 2018-09-29  16:47:33
 * @Description: User实体类
 */
public class User {

    /**
     * 1.属性
     */
    private int id;				//id
    private String name;		//姓名
    private String gender;		//性别
    private int age;			//年龄
    private String address;		//地址
    private String qq;			//qq
    private String email;		//email
    private String userName;	//账号
    private String passWord;	//密码

		//2.toString
			...
		//3.getter/setter
			...
		//4.无参构造
			...
		//5.有参构造
			... 
}

3、分页类封装

package com.mollen.domain;

import java.util.List;

/**
 * @ClassName:      PageBean
 * @Auther:         Mollen
 * @CreateTime:     2018-10-08  14:57:35
 * @Description:    分页属性封装类:PageBean
 */
public class PageBean<T> {
    private int totalCount;     //总纪录数
    private int totalPage;      //总页码
    private List<T> list;       //每页的数据
    private int currentPage;    //当前的页码
    private int rows;           //每页显示的纪录数
    
	//2.toString
		...
    //3.getter/setter
    	...
    //4.无参构造
    	...
    //5.有参构造
    	... 
}

4、Dao层

package com.mollen.dao;

import com.mollen.domain.User;
import java.util.List;
import java.util.Map;
/**
 * @ClassName:      UserDao
 * @Auther:         Mollen
 * @CreateTime:     2018-09-29  18:14:39
 * @Description:
 *                  UserDao用户操作接口
 */
public interface UserDao{
    /**
     * 1.分页查询用户
     */
    List<User> findUserByPage(int start , int rows,Map<String, String[]> condition);

    /**
     * 2.统计总记录数
     */
    int totalCount(Map<String, String[]> condition);
}
package com.mollen.dao.impl;

import com.mollen.dao.UserDao;
import com.mollen.domain.User;
import com.mollen.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName: UsereDaoImpl
 * @Auther: Mollen
 * @CreateTime: 2018-09-29  18:14:59
 * @Description: UserDao用户操作实现类
 */
public class UsereDaoImpl implements UserDao {
    /**
     * 创建JdbcTemplate对象
     */
    JdbcTemplate jtl = new JdbcTemplate(JDBCUtils.getDataSource()); 
    
	/**
     * 1.统计总纪录数
     * @param condition:封装查询参数
     * @return
     */
    @Override
    public int totalCount(Map<String, String[]> condition) {
        //1.定义模板初始化sql
        StringBuilder sb = new StringBuilder("select count(*) from user where 1 = 1 ");
        //2.定义参数的集合
        List<Object> params = new ArrayList<Object>();
        //3.遍历参数集合,追加查询条件
        Set<String> keySet = condition.keySet();
        for (String key : keySet) {
            //排除分页条件参数
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }
            //获取value
            String value = condition.get(key)[0];
            //判断value是否有值
            if(value != null && !"".equals(value)){
                //有值
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");
            }
        }
        //4.返回查询结果
        return jtl.queryForObject(sb.toString(),Integer.class,params.toArray());
    }
}
     
    /**
     * 2.分页查询
     * @param start:记录开始位置
     * @param rows:每页显示条数
     * @param condition:封装查询参数
     * @return
     */
    public List<User> findUserByPage(int start, int rows,Map<String, String[]> condition) {
		//1.定义sql模板
		StringBuilder sb = new StringBuilder("select * from user  where 1 = 1 ");
		//2.定义参数集合
		List<Object> params = new ArrayList<Object>();
		//3.遍历参数集合,追加查询条件
		Set<String> keySet = condition.keySet();  
		for (String key : keySet) {
			//跳过分页参数
			if("currentPage".equals(key) || "rows".equals(key)){
				continue;
			}
			//获取查询参数
			String value = condition.get(key)[0];
			//判断是否为空
			if(value != null && !"".equals(value)){
				//不为空给sql追加条件
				sb.append(" and "+key+" like ?  ");
				params.add("%"+value+"%");
			}
		}
		//添加分页查询
		sb.append(" limit ?,? ");
		//添加分页查询参数值
		params.add(start);
		params.add(rows);
		//4.返回查询结果
		return jtl.query(sb.toString(),new BeanPropertyRowMapper<User>(User.class),params.toArray());
    }    

5、Service层

package com.mollen.service;

import com.mollen.domain.PageBean;
import com.mollen.domain.User;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:      UserService
 * @Auther:         Mollen
 * @CreateTime:     2018-09-29  19:47:54
 * @Description:
 */
public interface UserService {
    /**
     * 1.分页查询
     */
    PageBean<User> findUserByPage(int currentPage, int rows,Map<String, String[]> condition);

}
package com.mollen.service.impl;

import com.mollen.dao.impl.UsereDaoImpl;
import com.mollen.dao.UserDao;
import com.mollen.domain.PageBean;
import com.mollen.domain.User;
import com.mollen.service.UserService;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserServiceImpl
 * @Auther: Mollen
 * @CreateTime: 2018-09-29  19:51:14
 * @Description: UserServiceImpl
 */
public class UserServiceImpl implements UserService {

    UserDao userDao = new UsereDaoImpl();
    
    /**
     * 1.分页查询
     * @param start
     * @param rows
     * @return
     */
    @Override
    public PageBean<User> findUserByPage(int currentPage, int rows,Map<String, String[]> condition) {
        //统计总条数
        int totalCount = userDao.totalCount(condition);
        //计算总页数
        int totalPage = (int)Math.ceil(totalCount*1.0 / rows);
        //计算开始索引
        int start=(currentPage-1)*rows;
        //查询当前页显示数据
        List<User> list = userDao.findUserByPage(start, rows,condition);
        //将数据封装到PageBean并返回
        return new PageBean<User>(totalCount,totalPage,list,currentPage,rows);
    }
}

6、Web层

package com.mollen.web;

import com.mollen.domain.PageBean;
import com.mollen.domain.User;
import com.mollen.service.UserService;
import com.mollen.service.impl.UserServiceImpl;

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.Map;

@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.乱码处理
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //2.获取分页参数
        int currentPage =  Integer.parseInt(request.getParameter("currentPage")==null?"1":request.getParameter("currentPage"));
        int rows =  Integer.parseInt(request.getParameter("rows")==null?"5":request.getParameter("rows"));

        //3.获取查询参数集合
        Map<String, String[]> condition = request.getParameterMap();

        //3.执行查询操作
        UserService service = new UserServiceImpl();
        PageBean<User> pageBean = service.findUserByPage(currentPage, rows,condition);

        //4.转发
        request.setAttribute("pageBean",pageBean);
        request.setAttribute("condition",condition);
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }
}

7、页面显示

<%--
  Created by IntelliJ IDEA.
  User: Mollen
  Date: 2018/9/30
  Time: 14:31
  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" %>
<!DOCTYPE html>
<html>
<head>
    <title>用户显示</title>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/jquery-2.1.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <style type="text/css">
        td, th {
            text-align: center;
        }
    </style>
</head>
<body>
<div style="margin: 0 auto;width: 70%">

    <div style="margin: auto;text-align:center">
        <h3>用户信息显示</h3>
        <br>
    </div>

    <div style="float: left;">
        <form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
            <div class="form-group">
                <label for="exampleInputName2">姓名</label>
                <input type="text" name="name" value="${condition.name[0]}" class="form-control" id="exampleInputName2">
            </div>
            <div class="form-group">
                <label for="exampleInputName3">籍贯</label>
                <input type="text" name="address" value="${condition.address[0]}" class="form-control" id="exampleInputName3">
            </div>

            <div class="form-group">
                <label for="exampleInputEmail2">邮箱</label>
                <input type="email" name="email" value="${condition.email[0]}" class="form-control" id="exampleInputEmail2">
            </div>
            <button type="submit" class="btn btn-default">查询</button>
        </form>
    </div>

    <div style="float: right;margin: 5px;">
        <a class="btn btn-primary" href="save.jsp">添加联系人</a>
        <a class="btn btn-primary" href="add.html">删除选中</a>
    </div>

    <div>
        <form id="form" action="" method="post">
            <table border="1" class="table table-bordered table-hover">
                <tr class="success">
                    <th><input type="checkbox" id="firstCb"></th>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>籍贯</th>
                    <th>QQ</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
                <c:forEach items="${pageBean.list}" var="user" varStatus="s">
                    <tr>
                        <td>
                            <input type="checkbox" name="uid" value="${user.id}">
                        </td>
                        <td>${s.count}</td>
                        <td>${user.name}</td>
                        <td>${user.gender}</td>
                        <td>${user.age}</td>
                        <td>${user.address}</td>
                        <td>${user.qq}</td>
                        <td>${user.email}</td>
                        <td>
                            <a class="btn btn-default btn-sm" href="/newLogin/findUserByIdServlet?id=${user.id}">修改</a>&nbsp;
                            <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id})">删除</a>
                        </td>
                    </tr>
                </c:forEach>
            </table>
        </form>
    </div>

    <div>
        <nav aria-label="Page navigation">
            <ul class="pagination">

                <!--上一页-->
                <c:if test="${pageBean.currentPage == 1}">
                    <li class="disabled">
                        <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pageBean.currentPage}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous">
                            <span aria-hidden="true"> &laquo; </span>
                        </a>
                    </li>
                </c:if>
                <c:if test="${pageBean.currentPage != 1}">
                    <li>
                        <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pageBean.currentPage - 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous">
                            <span aria-hidden="true"> &laquo; </span>
                        </a>
                    </li>
                </c:if>

                <!--中间页-->
                <c:forEach begin="1" end="${pageBean.totalPage}" var="i" >
                    <c:if test="${pageBean.currentPage == i}">
                        <li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
                    </c:if>
                    <c:if test="${pageBean.currentPage != i}">
                        <li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
                    </c:if>
                </c:forEach>

                <!--下一页-->
                <c:if test="${pageBean.currentPage == pageBean.totalPage}">
                    <li class="disabled">
                        <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pageBean.currentPage}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous">
                            <span aria-hidden="true"> &raquo; </span>
                        </a>
                    </li>
                </c:if>
                <c:if test="${pageBean.currentPage != pageBean.totalPage}">
                    <li>
                        <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pageBean.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous">
                            <span aria-hidden="true"> &raquo; </span>
                        </a>
                    </li>
                </c:if>

                <span style="font-size: 25px;margin-left: 5px;">
                    共${pageBean.totalCount}条记录,共${pageBean.totalPage}页
                </span>
            </ul>
        </nav>
    </div>
</div>
</body>
</html>

三、效果显示

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mollen/article/details/83023379
今日推荐