JavaWeb实现具体分页封装 港控/mmm° 2022-02-15 09:52 401阅读 0赞 ## 一、准备工作 ## **1、jar包:** ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW5nMTUwMTE0_size_16_color_FFFFFF_t_70] a. 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 b. mysql驱动包及连接池依赖 mysql-connector-java-5.1.37-bin.jar druid-1.0.9.jar c. 请求参数封装包 commons-beanutils-1.8.0.jar d. jsp依赖包 javax.servlet.jsp.jstl.jar jstl-impl.jar **2、js依赖** ![在这里插入图片描述][2019042411194986.png] a. jquery框架依赖文件 b. bootstap框架依赖文件 ## 二、代码实现 ## **1、jdbc配置** 导入jar包 : druid依赖包:druid-1.0.9.jar mysql驱动包: mysql-connector-java-5.1.37-bin.jar 配置文件:druid.properties # 驱动 driverClassName=com.mysql.jdbc.Driver # 数据库地址 url=jdbc:mysql://127.0.0.1:3306/my_db # 用户名 username=root # 密码 password=root # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000 创建JDBCUtils工具类 package com.mollen.demo03; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * @ClassNmme: JDBCUtils * @Author: Mollen * @CreateDate: 2018-09-07 16:44:42 * @Description: * Druid连接池工具类 */ public class JDBCUtils { /** * 1.定义成员变量 */ private static DataSource ds; /** * 2.加载数据源 */ static { try { Properties pro = new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("Druid.properties"); pro.load(is); ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 3.获取连接池对象 * @return */ public static DataSource getDataSource() { return ds; } /** * 4.获取数据库连接对象 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } } 注意: 1、参数解释,注意参数类型; 2、执行语句选择 增,删,改(DML)操作建议使用executeUpdate(); 查询(DQL)操作建议使用executeQuery() ; 需要对执行语句类型做出判断用execute() 3、数据库连接使用完毕必须释放资源 **2、实体类Model层封装** package com.mollen.model; /** * @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数据持久化层** -------------------UserDao------------------------------ 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); } -------------------UserDaoImpl------------------------------ 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: UserDaoImpl * @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服务层** -------------------UserService------------------------------ 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); } -------------------UserServiceImpl------------------------------ 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、后台控制逻辑Controller层** package com.mollen.controller; 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.、页面显示View层** <%-- 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> <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"> « </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"> « </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"> » </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"> » </span> </a> </li> </c:if> <span style="font-size: 25px;margin-left: 5px;"> 共${pageBean.totalCount}条记录,共${pageBean.totalPage}页 </span> </ul> </nav> </div> </div> </body> </html> ## 实现效果如下: ## ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW5nMTUwMTE0_size_16_color_FFFFFF_t_70 1] ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW5nMTUwMTE0_size_16_color_FFFFFF_t_70 2] 原文:[https://blog.csdn.net/mollen/article/details/83023379][https_blog.csdn.net_mollen_article_details_83023379] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW5nMTUwMTE0_size_16_color_FFFFFF_t_70]: /images/20220215/17ed6c32c7b74d76852bad763c453f43.png [2019042411194986.png]: /images/20220215/c8ed76b305024f75960080a087dbe40b.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW5nMTUwMTE0_size_16_color_FFFFFF_t_70 1]: /images/20220215/6f031ba5441b42938a144ca550b756a1.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW5nMTUwMTE0_size_16_color_FFFFFF_t_70 2]: /images/20220215/8641d2d320f44f9c863ac935701b199b.png [https_blog.csdn.net_mollen_article_details_83023379]: https://blog.csdn.net/mollen/article/details/83023379
还没有评论,来说两句吧...