Java項目之查詢後分頁

1、Jsp頁面:javascript

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>總經理頁面的員工信息版塊</title>
<link rel="stylesheet" href="layui/css/layui.css">
<script src="js/jquery.min.js"></script>
<style>
body{
width:100%;
}
/* 添加按鈕樣式  */
#updateList {
    margin: 0 auto;
    width: 300px;
    height: 250px;
    border: 1px solid #F00
}
</style>
</head>
<body>
    <!-- 員工信息版塊 -->
    <div>
        <form id="Form1" name="Form1"
            action="${pageContext.request.contextPath}/ConditionPersonServlet"
            method="post">
            <!--搜索欄  -->
            &nbsp;&nbsp;&nbsp;&nbsp;公司職位: <select name="ppid" id="pposition">
                <option value="">請選擇</option>
                <!-- 須要注意的是{}裏面不能有空格 -->
                <c:forEach items="${PositionList}" var="pl">
                    <option value="${pl.ppid}">${pl.pposition}</option>
                </c:forEach>
            </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;團隊: <select name="pteam" id="pteam">
                <option value="">請選擇</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;部門: <select name="pdid" id="pdepartment">
                <option value="">請選擇</option>
                <c:forEach items="${DepartmentList}" var="dl">
                    <option value="${dl.pdid}">${dl.pdepartment}</option>
                </c:forEach>
            </select> 
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <input type="submit" value="搜索" class="layui-btn layui-btn-normal">
            <!-- 信息表 -->
            <table class="layui-table">
                <colgroup>
                    <col width="150">
                    <col width="200">
                    <col>
                </colgroup>
                <thead>
                    <tr>
                        <th>員工編號</th>
                        <th>員工姓名</th>
                        <th>公司職位</th>
                        <th>所屬團隊</th>
                        <th>所屬部門</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <!-- varStatus="vs" 特有的屬性,循環變量 varStatus="vs" -->
                    <c:forEach items="${PageBean.list}" var="pro">
                        <tr>
                            <td width=10%>${pro.pid}</td>
                            <td width=15%>${pro.pname}</td>
                            <td width=15%>${pro.pposition}</td>
                            <td width=10%>${pro.pteam}</td>
                            <td width=20%>${pro.pdepartment}</td>
                            <td width=30%>
                    <!-- PersonList是當前登陸用戶的信息集合 -->
                                 <c:if test="${pro.pid==1}">
                                    <a
                                        href="${pageContext.request.contextPath}/PersonListByIdServlet?pid=${pro.pid}"
                                        id="updatebtn" class="layui-btn " style="display: none">修改</a>
                                    <a href="javascript:void(0)" onClick="del('${pro.pid}')"
                                        class="layui-btn  layui-btn-danger" style="display: none">辭退</a>
                                </c:if> 
                                <c:if test="${pro.pid!=1}">
                                    <a href="${pageContext.request.contextPath}/PersonListByIdServlet?pid=${pro.pid}"
                                        id="updatebtn" class="layui-btn ">修改</a>
                                    <a href="javascript:void(0)" onClick="del('${pro.pid}')"
                                        class="layui-btn  layui-btn-danger" style="margin-left:50px">辭退</a>
                                </c:if>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>

            <%-- 構建分頁導航 --%>
            <nav aria-label="Page navigation">
            <ul class="pagination">
                共有${PageBean.totalCount}&nbsp;個員工,共${PageBean.totalpage }&nbsp;頁,當前爲${PageBean.currentPage}&nbsp;頁
                &nbsp;
                <a
                    href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=1">首頁</a>
                <!-- 若是當前頁爲第一頁時,就沒有上一頁這個超連接顯示 -->
                <c:if test="${PageBean.currentPage ==1}">
                    <c:forEach begin="1" end="${PageBean.totalpage}" step="1" var="i">
                        <c:if test="${PageBean.currentPage == i}">
                        ${i}
                        </c:if>
                        <c:if test="${PageBean.currentPage != i}">
                            <a
                                href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${i}">${i}</a>
                        </c:if>
                    </c:forEach>
                    <a
                        href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${PageBean.currentPage+1}">下一頁</a>
                </c:if>
                &nbsp;
                <!-- 若是當前頁不是第一頁也不是最後一頁,則有上一頁和下一頁這個超連接顯示 -->
                <c:if
                    test="${PageBean.currentPage > 1 && PageBean.currentPage < PageBean.totalpage}">
                    <a
                        href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${PageBean.currentPage-1}">上一頁</a>
                    <c:forEach begin="1" end="${PageBean.totalpage}" step="1" var="i">
                        <c:if test="${PageBean.currentPage == i}">
                        ${i}
                    </c:if>
                        <c:if test="${PageBean.currentPage != i}">
                            <a
                                href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${i}">${i}</a>
                        </c:if>
                    </c:forEach>
                    <a
                        href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${PageBean.currentPage+1}">下一頁</a>
                </c:if>
                &nbsp;
                <!-- 若是當前頁是最後一頁,則只有上一頁這個超連接顯示,下一頁沒有 -->
                <c:if test="${PageBean.currentPage == PageBean.totalpage}">
                    <a
                        href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${PageBean.currentPage-1}">上一頁</a>
                    <c:forEach begin="1" end="${PageBean.totalpage}" step="1" var="i">
                        <c:if test="${PageBean.currentPage == i}">
                        ${i}
                    </c:if>
                        <c:if test="${PageBean.currentPage != i}">
                            <a
                                href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${i}">${i}</a>
                        </c:if>
                    </c:forEach>
                </c:if>

                <a
                    href="${pageContext.request.contextPath}/ConditionPersonServlet?currentPage=${PageBean.totalpage}">尾頁</a>
            </ul>
    </div>
</body>
</html>


<script type="text/javascript">
    /* 點擊刪除按鈕 */
function del(pid) {
        var isdel = confirm("您確認要辭退該員工嗎?(辭退即全部此人的信息均無)");
        if (isdel) {
            /* 除了form表單,其餘的都是get提交,都須要?  拼接參數 */
            window.location.href = "${pageContext.request.contextPath}/DeleteServlet?pid="
                    + pid;
        }
    }

    /* 回顯---找屬性值爲Pdepartment等的元素使其被選中*/
    $(function() {
        $("#pposition option[value='${Condition.ppid}']")
                .prop("selected", true);
    })

    $(function() {
        $("#pteam option[value='${Condition.pteam}']").prop("selected", true);
    })
    $(function() {
        $("#pdepartment option[value='${Condition.pdid}']").prop("selected",
                true);
    })
</script>

2、javaBean類:css

一、建立分頁類html

package domain;
//分頁用類
import java.util.ArrayList;
import java.util.List;
//爲了能多個地方調用這個,須要用泛型
public class PageBean<T> {
     //封裝當前頁
    private Integer currentPage;
    //總頁數
    private Integer totalpage;
    //每頁顯示條數
    private Integer currentCount;
    //總條數
    private Integer totalCount;
    //每頁顯示的數據
    private List<T> list = new ArrayList<T>();
    public Integer getCurrentPage() {
        return currentPage;
    }
    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }
    public Integer getTotalpage() {
        return totalpage;
    }
    public void setTotalpage(Integer totalpage) {
        this.totalpage = totalpage;
    }
    public Integer getCurrentCount() {
        return currentCount;
    }
    public void setCurrentCount(Integer currentCount) {
        this.currentCount = currentCount;
    }
    public Integer getTotalCount() {
        return totalCount;
    }
    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }
    public List<T> getList() {
        return list;
    }
    public void setList(List<T> list) {
        this.list = list;
    }
    @Override
    public String toString() {
        return "PageBean [currentPage=" + currentPage + ", totalpage=" + totalpage + ", currentCount=" + currentCount
                + ", totalCount=" + totalCount + ", list=" + list + "]";
    }
    
    
}

二、建立查詢所用的條件類java

package domain;

import java.io.Serializable;

//將搜索條件建立一個JavaBean---都是String類型的(這個跟原來的類中的類型無關)是須要判斷非空的
public class Condition implements Serializable{
    private String ppid;
    private String pteam;
    private String pdid;
    public String getPpid() {
        return ppid;
    }
    public void setPpid(String ppid) {
        this.ppid = ppid;
    }
    public String getPteam() {
        return pteam;
    }
    public void setPteam(String pteam) {
        this.pteam = pteam;
    }
    public String getPdid() {
        return pdid;
    }
    public void setPdid(String pdid) {
        this.pdid = pdid;
    }
    @Override
    public String toString() {
        return "Condition [ppid=" + ppid + ", pteam=" + pteam + ", pdid=" + pdid + "]";
    }

    
}

3、Dao層:jquery

// 根據條件在員工信息表中搜索
    public List<Message> getMessageByCondition(Condition condition, int index, Integer currentCount)
            throws SQLException {
        QueryRunner qr = new QueryRunner(MyDBUtils.getDataSource());
        String sql = "select * from person join position ON person.ppid=position.ppid JOIN department ON person.pdid=department.pdid where 1=1";
        // 須要將結果存在集合中(因數組長度不可變) DISTINCT去重
        ArrayList<Object> arr = new ArrayList<Object>();
        // trim()是去掉首尾空格
        if (condition.getPpid() != null && condition.getPpid() != "") {
            // sql += " and pposition like ?"; && condition.getPteam() != ""
            // arr.add("%" + condition.getPposition() + "%");
            sql += " and person.Ppid=?";
            arr.add(condition.getPpid());
        }
        if (condition.getPdid() != null && condition.getPdid() != "") {
            sql += " and person.Pdid=?";
            arr.add(condition.getPdid());
        }
        if (condition.getPteam() != null && condition.getPteam() != "") {
            sql += " and pteam=?";
            arr.add(condition.getPteam());
        }
        sql += " limit ?,?";
        arr.add(index);
        arr.add(currentCount);
        List<Message> list = qr.query(sql, new BeanListHandler<Message>(Message.class), arr.toArray());
        return list;
    }

二、Service層:web

// 根據condition查詢員工信息
    public PageBean<Message> getMessageByCondition(Condition condition, Integer currentPage, Integer currentCount) {

        // 建立PageBean
        PageBean<Message> pageBean = new PageBean<Message>();
        // 設置當前頁
        pageBean.setCurrentPage(currentPage); // 設置每頁顯示的條數
        pageBean.setCurrentCount(currentCount); // 設置總條數
        int totalCount = 0;
        try {
            totalCount = personMessageDao.getTotalCount();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        pageBean.setTotalCount(totalCount);
        // 計算總頁數=總條數/每頁顯示的條數 //先整數*1.0變成小數,獲得有小數點的-->向上取整,獲得double類型-->再轉爲int
        Integer totalPage = (int) Math.ceil(totalCount * 1.0 / currentCount);
        // 設置總頁數
        pageBean.setTotalpage(totalPage);
        // 設置每頁顯示的數據 // select *fromproduct limit (當前頁-1)*每頁顯示的條數 , 每頁顯示的條數
        int index = (currentPage - 1) * currentCount;
        // 定義
        List<Message> list = null;
        try {
            list = personMessageDao.getMessageByCondition(condition, index, currentCount);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        pageBean.setList(list);

        return pageBean;

    }

4、Web層:sql

package web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import dao.PersonListDao;
import domain.Condition;
import domain.Department;
import domain.Message;
import domain.PageBean;
import domain.Person;
import domain.Position;
import service.PersonListService;
import service.PersonMessageService;

//當職位在總經理之下則進入此頁面---員工信息裏的分頁和查詢
public class PersonListServlet extends HttpServlet {
    private PersonListService personListService = new PersonListService();
    private PersonMessageService personMessageService = new PersonMessageService();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // post解決亂碼
        request.setCharacterEncoding("utf-8");
        // 得到全部條件參數所在的Map
        Map<String, String[]> map = request.getParameterMap();
        // 建立Condition對象
        Condition condition = new Condition();
        // 用BeanUtils進行封裝
        try {
            BeanUtils.populate(condition, map);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 獲取當前頁
        String currentPageStr = request.getParameter("currentPage");
        // 須要設置默認--當點擊進來的時候顯示第一頁
        if (currentPageStr == null) {
            currentPageStr = "1";
        }
        // 將字符串轉爲Integer
        Integer currentPage = Integer.parseInt(currentPageStr);
        // 設置每頁顯示的條數
        Integer currentCount = 8;
        // 調用service層方法
        // 得到全部的職位的list-根據職位表把搜索的信息整合到主表中
        List<Position> listp = personMessageService.getPosition();
        // 得到全部的部門的list-根據職位表把搜索的信息整合到主表中
        List<Department> listd = personMessageService.getDepartment();
        // 獲取員工信息的列表
        PageBean<Message> list = personMessageService.getMessageByCondition(condition, currentPage, currentCount);
        // 向域中存值
        request.getSession().setAttribute("PageBean", list);
        request.getSession().setAttribute("PositionList", listp);
        request.getSession().setAttribute("DepartmentList", listd);
        // 回顯---將選擇的選項進行顯示在頁面內
        request.getSession().setAttribute("Condition", condition);
        request.getRequestDispatcher("PersonList.jsp").forward(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
相關文章
相關標籤/搜索