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>

發佈了17 篇原創文章 · 獲贊 18 · 訪問量 2840
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章