用户信息复杂条件查询功能
用户信息复杂条件查询功能
分析:
UserDao进行改造:加了一个 Map<String, String[]> condition
/** * 查询总记录数 * @return * @param condition */ int findTotalCount(Map<String, String[]> condition); /** * 分页查询每页记录 * @param start * @param rows * @param condition * @return */ List<User> findByPage(int start, int rows, Map<String, String[]> condition);
UserDaoImpl进行改造:注意1 = 1 和 有值后拼接的空格 " and "+key+" like ? " 要不拼接sql 的时候会出现错误 (1and....)不正确的SQL
@Override public int findTotalCount(Map<String, String[]> condition) { //定义模板初始化sql String sql = "select count(*) from user where 1 = 1 "; StringBuilder sb = new StringBuilder(sql); //遍历map Set<String> keySet = condition.keySet(); //定义参数的集合 List<Object> params = new ArrayList<Object>(); 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+"%");//加条件的值 } } return template.queryForObject(sb.toString(),Integer.class,params.toArray()); } @Override public List<User> findByPage(int start, int rows, Map<String, String[]> condition) { String sql = "select * from user where 1=1"; StringBuilder sb = new StringBuilder(sql); //遍历map Set<String> keySet = condition.keySet(); //定义参数的集合 List<Object> params = new ArrayList<Object>(); 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+"%");//加条件的值 } } //添加分页查询 sb.append(" limit ?,? "); //添加分页查询参数值 params.add(start); params.add(rows); return template.query(sb.toString(),new BeanPropertyRowMapper<User>(User.class),params.toArray()); }
UserService改造:
/** * 分页条件查询 * @param _currentPage * @param _rows * @param condition * @return */ PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition);
UserServiceImpl改造:
@Override public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) { int currentPage = Integer.parseInt(_currentPage); int rows = Integer.parseInt(_rows); if (currentPage< 1){ currentPage = 1; } //创建空的PageBean对象 PageBean<User> pb = new PageBean<User>(); //调用dao查询总记录数 int totalCount = dao.findTotalCount(condition); pb.setTotalCount(totalCount); //计算总页码 int totalPage = (totalCount % rows) == 0 ? totalCount/rows : (totalCount/rows) +1; //int totalPage = (int)Math.ceil((double)totalCount / rows); if (currentPage > totalPage){ currentPage = totalPage; } //设置参数 pb.setCurrentPage(currentPage); pb.setRows(rows); //调用dao查询list集合 //计算开始的记录索引 int start = (currentPage-1) * rows; List<User> list = dao.findByPage(start,rows,condition); pb.setList(list); pb.setTotalPage(totalPage); return pb; }
FindUserByPageServlet改造:
@WebServlet("/findUserByPageServlet") public class FindUserByPageServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //获取参数 String currentPage = request.getParameter("currentPage");//当前页码 String rows = request.getParameter("rows");//每页显示条数 if (currentPage == null || "".equals(currentPage)){ currentPage = "1"; } if (rows == null || "".equals(rows)){ rows = "5"; } //获取条件查询参数 Map<String, String[]> condition = request.getParameterMap(); //调用service查询 UserServiceImpl service = new UserServiceImpl(); PageBean<User> pb = service.findUserByPage(currentPage,rows,condition); //将PageBean存入request request.setAttribute("pb",pb); request.setAttribute("condition",condition);//将查询条件存入request //转发到list.jsp页面 request.getRequestDispatcher("/list.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
list.jsp改造:
页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id) { //判断用户安全提示 if (confirm("确定要删除吗?")){ location.href = "${pageContext.request.contextPath}/delUserServlet?id="+id; } } window.onload = function () { //给删除选中按钮添加单击事件 document.getElementById("delSelected").onclick = function () { if (confirm("确定要删除选中的吗?")){ var flag = false; //判断是否有选中条目 var cbs = document.getElementsByName("uid"); for (let i = 0; i <cbs.length; i++) { if (cbs[i].checked){ //有一个条目选中 flag = true; break; } } if (flag){//有条目被选中 //表单提交: document.getElementById("form").submit(); } } } //1.获取第一个cb document.getElementById("firstCb").onclick = function () { //获取下边列表的所有的cd var cbs = document.getElementsByName("uid"); //遍历 for (let i = 0; i <cbs.length; i++) { //设置这些cbs[i]的checked状态=firstCb.的checked状态 cbs[i].checked = this.checked; } } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <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="text" name="email" value="${condition.elail[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="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a> </div> <form id="form" action="${pageContext.request.contextPath}/delSelectedServlet" 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="${pb.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="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a> </td> </tr> </c:forEach> </table> </form> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <c:if test="${pb.currentPage == 1}"> <li class="disabled"> </c:if> <c:if test="${pb.currentPage != 1}"> <li> </c:if> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.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:forEach begin="1" end="${pb.totalPage}" var="i"> <c:if test="${pb.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="${pb.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="${pb.currentPage == pb.totalPage}"> <li class="disabled"> </c:if> <c:if test="${pb.currentPage != pb.totalPage}"> <li> </c:if> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px;margin-left: 5px"> 共${pb.totalCount}条记录,共${pb.totalPage}页 </span> </ul> </nav> </div> </div> </body> </html>