java实现复杂条件查询

分析:

我是基于分页情况下使用复杂条件查询,分页在我的上一篇博客,有兴趣的朋友可以去阅读一下。[java实现分页功能(一)]复杂条件查询最关键的一点就是模糊查询的使用,在这我给大家介绍一下模糊查询的语法。
Select *from 表名 where 字段名 like 对应值(字符串);
模糊查询中最关键的就是标识符的使用比如%,_,*,?,[]等
1.%表示零个或多个字符的任意字符串:

 (1)select *from user where name like' 李% '表示搜索以李字开头的所有名字

 (2)select *from user where name like' %四 '表示搜索以四结尾的所有名字

  (3)select *from user where name like' %李% ' 表示搜索所有包含的名字

2._表示任意单个字符

(1)select *from user where name like' _四 '表示搜索以四结尾的的所有名字

3.*通配符,代表多个字符(a*c代表abc,aBc,aAc,adasflac等多个字符)

(1)select *from user where name like' 李`*` '表示搜索以李字开头的所有名字

4.?通配符,代表单个字符(b?b表示bab,bbb,bcb等)

 (1)select *from user where name like' 李?'表示搜索以李字开头两个字的所有名字

5.[]表示指定范围

 (1)select *from table where name like' %[!0-9]% ' 表示搜索不包含数字的姓名

Servlet

package cn.easyArch.web.Servlet;

import cn.easyArch.domain.PageBean;
import cn.easyArch.domain.User;
import cn.easyArch.service.UserService;
import cn.easyArch.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 {*

    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="8";
    }
    //获取条件查询参数
    Map<String,String[]> condition=request.getParameterMap();

    //调用Service查询
    UserService service=new UserServiceImpl();
    PageBean<User> pb=service.findUserByPage(currentPage,rows,condition);
    System.out.println(pb);

    //将pagebean存入request
    request.setAttribute("pb",pb);
    //将查询条件存入request
    request.setAttribute("condition",condition);
    //转发到list.jsp
    request.getRequestDispatcher("/list.jsp").forward(request,response);

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
}

}
Service

 *public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {*

//类型转换
int currentPage=Integer.parseInt(_currentPage);
int rows=Integer.parseInt(_rows);

//保持点击第一页状态
if (currentPage <=0){
    currentPage=1;
}

//创建空的PageBean对象
PageBean<User> pb=new PageBean<User>();

//设置参数
pb.setCurrentPage(currentPage);
pb.setRows(rows);

//调用dao查询总记录数
int totalCount=dao.findTotalCount(condition);
pb.setTotalCount(totalCount);

//调用dao查询list集合
//计算开始的记录索引
int start=(currentPage-1)*rows;
List<User> list=dao.findByPage(start,rows,condition);
pb.setList(list);

//计算总页码
int totalPage = (totalCount % rows) == 0 ? totalCount/rows:(totalCount/rows)+1;
pb.setTotalPage(totalPage);
if (currentPage >= totalPage){
    currentPage=totalPage;
}
return pb;

}
Dao

 public int findTotalCount(Map<String, String[]> condition) {

//定义模板sql
String sql="select count(*) from userms where 1 = 1 ";
StringBuilder sb=new StringBuilder(sql);

//遍历map
Set<String> keySet=condition.keySet();

//定义参数的集合
List<Object>params =new ArrayList<Object>();
for (String key:keySet){

    //排除分页条件参数currentPage和rows
    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 ?");
        //?d的值
        params.add("%"+value+"%");
    }
}
return template.queryForObject(sb.toString(),Integer.class,params.toArray());

}

//根据条件查询

  public List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
String sql="select *from userms 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是否有值
    // 注意and和like一定要加空格
    sb.append(" and "+key+" like ? ");
    params.add("%"+value+"%");
}

 //添加分页查询

sb.append("limit ?,? ");
//添加分页查询参数值
params.add(start);
params.add(rows);
System.out.println(sql);
System.out.println(params);
return template.query(sb.toString(),new BeanPropertyRowMapper<User>
(User.class),params.toArray());
 }

前台

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- 网页使用的语言 -->
<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.οnlοad=function () {
            //给删除选中按钮添加单击事件
            document.getElementById("delSelected").οnclick=function () {
                if (confirm("您确定要删除选中条目吗?"))
                    //表单提交
                    document.getElementById("form").submit();
            }

            //1.获取第一个cb
            document.getElementById("firstCb").οnclick=function () {
                //获取下表所有的cb
                var cbs=document.getElementsByName("uid");
                //遍历
                for (var 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.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="${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>&nbsp;
                    <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=8&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</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=8&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=8&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=8&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}&${pb.totalPage}" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                <span style="font-size: 14px;margin-left: 5px; color: gray">
                    共${pb.totalCount}条记录,共${pb.totalPage}页
                </span>
            </ul>
        </nav>
    </div>
</div>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值