【JAVA技术库】分页模糊查询 进阶版

先上效果图这里写图片描述

cdsp_studentManager.jsp 主页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <meta charset="utf-8" />
    <base href="<%=basePath%>">

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- 初始设置 : 页面编码,IE兼容,屏幕自适应-->

    <!-- 设置页面的缩放模式-->
    <meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <!-- bootstrap的依赖库-->
    <script src="bootstrap/js/jquery-3.1.1.js"></script>
    <!-- 导入bootstrap的核心样式文件-->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
    <!-- 导入bootstrap的主题样式文件-->
    <link rel="stylesheet" href="bootstrap/css/bootstrap-theme.min.css" />
    <!-- bootstrap的核心js库-->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <!--  以下两个js文件,是为了让IE6/7/8能够使用html5标签   -->
    <!--[if lt IE 9]>
    <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!--引入表单验证插件:bootstrapvalidator-0.5.2-dist-->
    <link type="text/css" rel="stylesheet" href="bootstrapvalidator-0.5.2-dist/dist/css/bootstrapValidator.min.css" />
    <script type="text/javascript" src="bootstrapvalidator-0.5.2-dist/dist/js/bootstrapValidator.min.js" ></script>
    <script type="text/javascript" src="bootstrapvalidator-0.5.2-dist/dist/js/language/zh_CN.js"></script>
    <!--引入图标的样式库-->
    <link type="text/css" href="font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
    <%--导入其他的CSS样式和JS文件--%>
    <link href="css/basic.css" rel="stylesheet" />
    <link href="css/custom.css" rel="stylesheet" />

    <title>学生管理</title>
</head>
<body>
<%--allRecorders  模糊查询查到的数据量--%>
<%--lineSize 每页的数据量--%>
<%--currentPage  当前页--%>
<%--pageSize 一共几页--%>
<%--keyWord 关键字--%>
<%
    String url = "/jsp/cdsp_information/manager/MStudentList.jsp";
    int currentPage = 1;
    String keyWord = "";//默认的关键字
    int lineSize = 5;//每页显示的数据数
    int allRecorders = 0;//保存总记录数
    int pageSize = 0;//保存查询总页数
    String column = "UserID";//定义默认的查询列
    String columnData = "用户账号:UserID|用户姓名:UserName|用户状态:UserStatus";//可操作的查询列

    if(session.getAttribute("currentPage")!=null){//表示有当前页
        currentPage = Integer.parseInt(session.getAttribute("currentPage").toString());//取得当前页
        System.out.println("!!!!!!!!!!!!!!!!!!currentPage:"+currentPage);
    }
    if(session.getAttribute("allRecorders")!=null){//表示有总数据量
        allRecorders = Integer.parseInt(session.getAttribute("allRecorders").toString());//取得总数据量
        System.out.println("!!!!!!!!!!!!!!!!!!allRecorders:"+allRecorders);
    }
    if(session.getAttribute("pageSize")!=null){//表示有总页数
        pageSize = Integer.parseInt(session.getAttribute("pageSize").toString());//取得总页数
        System.out.println("!!!!!!!!!!!!!!!!!!pageSize:"+pageSize);
    }
    if(session.getAttribute("lineSize")!=null){//表示有每页数据量
        lineSize = Integer.parseInt(session.getAttribute("lineSize").toString());//取得每页数据量
        System.out.println("!!!!!!!!!!!!!!!!!!lineSize:"+lineSize);
    }
    if(session.getAttribute("keyWord")!=null){//表示有查询的关键字
        keyWord =  session.getAttribute("keyWord").toString();//将取得的关键字进行转换
        System.out.println("!!!!!!!!!!!!!!!!!!keyWord:"+keyWord);
    }
    if(session.getAttribute("column")!=null){//表示有查询的检索列
        column = session.getAttribute("column").toString();
        System.out.println("!!!!!!!!!!!!!!!!!!column:"+column);
    }
%>
<div id="wrapper">
    <%--引入登陆页面的头文件 开始--%>
    <jsp:include page="cdsp_infoMheader.jsp"></jsp:include>
    <%--引入登陆页面的头文件 结束--%>

    <!--主体部分-->
    <div id="page-wrapper">
        <div id="page-inner">
            <%--面包屑导航--%>
            <ol class="breadcrumb">
                <li>用户管理</li>
                <li>学生管理</li>
            </ol>
            <div id="spiltSearchDiv">
                <jsp:include page="/jsp/cdsp_information/manager/split_page_search.jsp">
                    <jsp:param name="columnData" value="<%=columnData%>"></jsp:param>
                    <jsp:param name="keyWord" value="<%=keyWord%>"></jsp:param>
                    <jsp:param name="allRecorders" value="<%=allRecorders%>"></jsp:param>
                    <jsp:param name="column" value="<%=column%>"></jsp:param>
                    <jsp:param name="pageSize" value="<%=pageSize%>"></jsp:param>
                </jsp:include>
            </div>
            <%--学生管理---操作栏---结束--%>

            <%--设计一个创建学生用户的模态对话框---开始--%>
            <%---- student(studentID, sStatus,managerID, studentName, studentPassword, sIdentity, sLastTime)--%>
            <div class="modal fade" tabindex="-1" id="creStudent">
                <div class="modal-dialog">
                    <div class="modal-content">

                    </div><!--设计对话框的内容结束-->
                </div><!--设计对话框结束-->
            </div><!--设计对话框模块结束-->
            <%--创建学生用户的模态对话框---结束--%>
            <br>
            <%--学生管理---查询栏---开始--%>
            <h1>${QueryResult}</h1>
            <c:if test="${listByStudent != null}">
                <%--查询结果不为空--%>
                <table class="table table-bordered">
                    <tr>
                        <th><input type="checkbox" id="selAll" onclick="checkboxSelect(this,'UserNum')"></th>
                        <th>学生学号</th>
                        <th>学生姓名</th>
                        <th>当前状态</th>
                        <th>最后一次登录时间</th>
                        <th>操作</th>
                    </tr>
                        <%--查询查询结果--%>
                    <c:forEach items="${listByStudent}" var="student">
                        <%--对数据进行依次循环输出 -- student(studentID, sStatus,managerID, studentName, studentPassword, sIdentity, sLastTime)--%>
                        <tr>
                                <%--<td>${item.itemID}</td>--%>
                                <%--<td>${item.itemName}</td>--%>
                                <%--<td>${item.itemNote}</td>--%>
                            <td><input type="checkbox" name="UserNum" id="UserNum" value="${student.studentID}"></td>
                            <td>${student.studentID}</td>
                            <td>${student.studentName}</td>
                            <td>
                                <c:if test="${student.sStatus == 1}">
                                    在线
                                </c:if>
                                <c:if test="${student.sStatus == 2}">
                                    不在线
                                </c:if>
                            </td>
                            <td>${student.sLastTime}</td>
                            <td>
                                <a href="/jsp/cdsp_information/manager/UserInfo.jsp?UserID=${student.studentID}&UserName=${student.studentName}" class="btn btn-success" data-toggle="modal" data-target="#UserInfo"><i class="fa fa-search"></i> 查看</a>
                                <a class="btn btn-info" href="/jsp/cdsp_information/manager/cdsp_reStudentPasswordform.jsp?studentID=${student.studentID}" data-toggle="modal" data-target="#rePasswordModel"><i class="fa fa-edit"></i> 修改密码</a>
                                <a href="/jsp/cdsp_information/manager/MDelUser.jsp?MuserID=${student.studentID}" id="MDelUser" class="btn btn-danger" onclick="return delUser()"><i class="fa fa-trash-o"></i> 删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                </table>
                <%--批量删除--%>
                <td colspan="5"><input onclick="DelSelectUser('<%=basePath%>jsp/cdsp_information/manager/MDelSelectUser.jsp','UserAllNum','UserNum')" type="button" class="btn btn-danger" value="批量删除选中学生信息"></td>
                <%--分页栏--%>
            </c:if>
                <div id="splitBarDiv">
                    <jsp:include page="/jsp/cdsp_information/manager/split_page_bar.jsp">
                        <jsp:param name="currentPage" value="<%=currentPage%>"></jsp:param>
                        <jsp:param name="lineSize" value="<%=lineSize%>"></jsp:param>
                        <jsp:param name="column" value="<%=column%>"></jsp:param>
                        <jsp:param name="keyWord" value="<%=keyWord%>"></jsp:param>
                        <jsp:param name="allRecorders" value="<%=allRecorders%>"></jsp:param>
                        <jsp:param name="url" value="<%=url%>"></jsp:param>
                    </jsp:include>
                </div>
            <%--学生管理---查询栏---结束--%>
        </div>
        <!--设计修改密码的模态对话框模块-->
        <div class="modal fade" tabindex="-1" id="rePasswordModel">
            <div class="modal-dialog">
                <div class="modal-content">

                </div><!--设计对话框的内容结束-->
            </div><!--设计对话框结束-->
        </div><!--设计对话框模块结束-->

        <!--设计用户信息的模态对话框模块-->
        <div class="modal fade" tabindex="-1" id="UserInfo">
            <div class="modal-dialog">
                <div class="modal-content">

                </div><!--设计对话框的内容结束-->
            </div><!--设计对话框结束-->
        </div><!--设计对话框模块结束-->
    </div><!--主体部分-->
</div>

<%--引入尾部   开始--%>
<jsp:include page="/jsp/cdsp_information/cdsp_infofooter.jsp"></jsp:include>
<%--引入尾部   结束--%>
<script src="js/jquery.metisMenu.js"></script>
<script src="js/custom.js"></script>
<script type="text/javascript">
    $(function(){/* 文档加载,执行一个函数*/
        $('#StudentIDQueryFrom').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {/*input状态样式图片*/
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {/*验证:规则*/
                studentID: {
                    message: '学生ID无效',
                    validators: {
                        notEmpty: {
                            message: '查询的学生学号不能为空'
                        }
                    }
                }
            }
        });
    });
</script>
<script type="text/javascript">
    $(function(){/* 文档加载,执行一个函数*/
        $('#StudentNameQueryFrom').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {/*input状态样式图片*/
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {/*验证:规则*/
                studentName: {
                    message: '学生姓名无效',
                    validators: {
                        notEmpty: {
                            message: '查询的学生姓名不能为空'
                        }
                    }
                }
            }
        });
    });
</script>

<script type="text/javascript">
    function delUser(){
        if(window.confirm('请慎重选择是否删除该学生账户!是否删除?')){
            if(window.confirm('请再次确认是否删除!')){
                //alert("确定");
                return true;
            }else{
                //alert("取消");
                return false;
            }
        }else{
            //alert("取消");
            return false;
        }
    }
</script>
<script type="text/javascript">
    //    全选操作
    //    function checkboxSelect(元素名字){
    function checkboxSelect(obj,eleName){
        var item = document.all(eleName);
        console.log(item.length == undefined);//打印
        if(item.length == undefined){//表示只有一个元素,不是数组
            document.getElementById(eleName).checked = this.checked;//当前触发属性
        }else{
            for (var x = 0 ; x < item.length ; x++){
                item[x].checked = obj.checked;
            }
        }
    }
</script>
<script type="text/javascript">
    //    删除选中的学生用户操作
    //    function DelSelectUser(要删除的操作路径,后端提交的参数名称要删除的传递过来的参数名称,元素名称取得数据的ID名称){
    function DelSelectUser(url,paramName,eleName){
        var data = "";//保存所有要删除的数据编号
        //但是数据有可能是数组,也有可能只有一个
        var item = document.all(eleName);
        var count = 0;//保存要删除的数据个数
        //判断是否有要删除的数据
        if(item.length == undefined){//表示只有一个元素,不是数组
            if (document.getElementById(eleName).checked == true){
                //表示有数据选中,可以删除
                data += document.getElementById(eleName).value;//取出数据
                count ++;
            }
        }else{
            for(var x = 0 ; x < item.length ; x++ ){
                if(item[x].checked == true){
                    //被选中
                    count++;
                    data += item[x].value+"|";
                }
            }
        }
        if (count > 0){
            //有要删除的数据
//            alert(data);
            console.log(data);
            //进行提示是否要删除选中的数据!
            if(window.confirm("你正在进行删除操作!请确定要删除选中的数据吗?")){
                //再次提示是否删除
                if(window.confirm("请再一次确认是否要删除选中的数据?")){
                    //确定要删除,进行跳转
                    console.log(url + "?" + paramName + "=" + data);
                    window.location = url + "?" + paramName + "=" + encodeURIComponent(data);
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            //没有要删除的数据,并进行提示
            alert("你还未选择要删除的数据!!");
        }
    }
</script>
<script type="text/javascript">
    // 定义一个清空查询关键词的函数方法
    function resetKeyWord(){
        console.log("触发resetKeyWord事件!");//打印
        //    $选择器   : $("#表单的id") edit_note_form 表单 返回一堆的表单组,所以需要使用下标的方式,调用bootstrap提供的reset()方法
        document.getElementById('kw').value = '';
    }
</script>
</body><!--body结束-->
</html><!--html结束-->

split_page_bar.jsp 分页栏页面

<%@ page pageEncoding="UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
%>
<%--
    代码的引入过程
    <div id="splitBarDiv">
    <jsp:include page="split_page_bar.jsp">
        <jsp:param name="currentPage" value="<%=currentPage%>"></jsp:param>
        <jsp:param name="lineSize" value="<%=lineSize%>"></jsp:param>
        <jsp:param name="column" value="<%=column%>"></jsp:param>
        <jsp:param name="keyWord" value="<%=keyWord%>"></jsp:param>
        <jsp:param name="allRecorders" value="<%=allRecorders%>"></jsp:param>
        <jsp:param name="url" value="<%=url%>"></jsp:param>
    </jsp:include>
</div>
--%>

<%//设置由外部接收的数据
    String url = null;
    int currentPage = 1;//当前页
    int lineSize = 5;//每页数据数
    String column = null;//检索列
    String keyWord = null;//关键词
    int allRecorders = 0;//总记录数
    int pageSize = 0 ;//总页数
    int lsData [] = new int [] {1,5,10,15,20,30,50,100} ;//每页显示多少条数据
%>

<%//接收外部传递的参数
    try {
        currentPage = Integer.parseInt(request.getParameter("currentPage"));
        System.out.println("jsp/cdsp_information/manager/split_page_bar.jsp:currentPage:"+currentPage);
    } catch (Exception e) {}
    try {
        allRecorders = Integer.parseInt(request.getParameter("allRecorders"));
        System.out.println("jsp/cdsp_information/manager/split_page_bar.jsp:allRecorders:"+allRecorders);
    } catch (Exception e) {}
    try {
        lineSize = Integer.parseInt(request.getParameter("lineSize"));
        System.out.println("jsp/cdsp_information/manager/split_page_bar.jsp:lineSize:"+lineSize);
    } catch (Exception e) {}
    column = request.getParameter("column") ;
    keyWord = request.getParameter("keyWord") ;
    url = request.getParameter("url") ;
%>

<%//计算总页数
    if (allRecorders > 0) {
        pageSize = (allRecorders + lineSize - 1) / lineSize ;
    } else {   // 没有记录
        pageSize = 1 ;
    }
%>
<%
    System.out.println("split_page_bar.jsp的keyWord;"+keyWord);
%>

<script type="text/javascript">
    function goSplit(vcp) {    // 根据外部传递的cp内容进行操作
        console.log("触发goSplit事件!");//打印
        var eleLs = document.getElementById("lsSel").value ;//取得显示数据量
        try {
            var eleKw = document.getElementById("kw").value ;//取得关键字
            var eleCol = document.getElementById("colSel").value ;//取得查询列的值
            window.location = "<%=url%>?cp=" + vcp + "&ls=" + eleLs + "&kw=" + eleKw + "&col=" + eleCol  ;
        } catch (Exception) {//如果出现异常,说明没有关键字和检索列
            window.location = "<%=url%>?cp=" + vcp + "&ls=" + eleLs  ;
        }
    }
</script>

<input type="button" class="btn btn-default" value="首页" onclick="goSplit(1)" <%=currentPage == 1 ? "disabled" : ""%>>
<input type="button" class="btn btn-default" value="上一页" onclick="goSplit(<%=currentPage-1%>)" <%=currentPage == 1 ? "disabled" : ""%>>
<input type="button" class="btn btn-default" value="下一页" onclick="goSplit(<%=currentPage+1%>)" <%=currentPage == pageSize ? "disabled" : ""%>>
<input type="button" class="btn btn-default" value="尾页" onclick="goSplit(<%=pageSize%>)" <%=currentPage == pageSize ? "disabled" : ""%>>
<%--//添加一个下拉列表框--%>
跳转到:<select id="cpSel" onchange="goSplit(this.value)">
<%--动态控制的option--%>
<%
    for (int x = 1;x <= pageSize;x++){
%>
<option value="<%=x%>" <%=currentPage == x ? "selected" : ""%>><%=x%></option>
<%
    }
%>
</select>页&nbsp;每页显示:
<select id="lsSel" onchange="goSplit(1)">
    <%
        for (int x = 0 ; x<lsData.length ;x++){
    %>
    <option value="<%=lsData[x]%>" <%=lineSize == lsData[x] ? "selected" : ""%>><%=lsData[x]%></option>
    <%
        }
    %>
</select>
行记录

split_page_search.jsp 搜索栏页面

<%@ page pageEncoding="UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
%>
<%
    String columnData = null;//查询的数据列
    String keyWord = null;//查询的关键字
    String column = null;//查询的
    int allRecorders = 0;//查询的总数据量
    int pageSize  = 0 ;//查询的总页数
%>
<%//接收页面的接收列
    try{
        allRecorders = Integer.parseInt(request.getParameter("allRecorders"));
    }catch (Exception e){}
    try{
        pageSize = Integer.parseInt(request.getParameter("pageSize"));
    }catch (Exception e){}
    columnData = request.getParameter("columnData");
    keyWord = request.getParameter("keyWord");
    column = request.getParameter("column");
%>
<form class="form-inline">
    <div class="form-group">
            <%
                if (columnData!=null){
            %>
            <select  class="form-control" id="colSel">
                <%
                    String result[] = columnData.split("\\|");
                    for (int x = 0 ; x < result.length ; x ++){
                        String temp[] = result[x].split(":");
                %>
                <option value="<%=temp[1]%>" <%=column.equals(temp[1])?"selected":""%>><%=temp[0]%></option>
                <%
                    }
                %>
            </select>
            <%
                }
            %>
            <input type="text" class="form-control" placeholder="请输入查询关键字" name="kw" id="kw" value="<%=keyWord%>">
            <%
                System.out.println("split_page_search.jsp的keyWord;"+keyWord);
                System.out.println("split_page_search.jsp的column;"+column);
            %>
            <!--设计一个清空按钮-->
            <%--<button class="btn btn-danger " onclick="resetKeyWord()"><i class="fa fa-remove"></i> 清空查询关键字</button>--%>
            <input class="btn btn-danger " type="button" value="清空关键字" onclick="resetKeyWord()">
            <!--设计一个按照学生姓名模糊查询的按钮-->&ensp;
            <%--<button class="btn btn-success" onclick="goSplit(1)"><i class="fa fa-search"></i> 开始检索</button>--%>
            <input type="button" class="btn btn-success" value="开始检索" onclick="goSplit(1)"><br>
    </div>
</form>
<br>
<form action="StudentAllQuery.action" method="post"  class="form-inline" id="StudentAllQueryFrom">
    <button type="submit" class="btn btn-success" disabled="true"><i class="fa fa-list"></i> 查询全部学生</button>
    <!--设计一个创建学生用户的按钮-->
    <a class="btn btn-success" href="/jsp/cdsp_information/manager/creStudent.html" data-toggle="modal" data-target="#creStudent"><i class="fa fa-user-plus"></i>创建学生用户</a>
    <button type="" class="btn btn-success"><i class="fa fa-list"></i> Excel导入学生用户</button>
</form><!--定义Form的内联模式的表单结束-->
<br>
<span>一共查询到<%=allRecorders%>条记录,一共有<%=pageSize+1%></span><br>
<%--,一共有<%=pageSize%>页。--%>

MStudentList.jsp 主页面转控制层页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--cp=1&ls=5&kw=11&col=UserStatus--%>
<%
    int currentPage = 1;
    String keyWord = "";//默认的关键字
    int lineSize = 5;//每页显示的数据数
    int allRecorders = 0;//保存总记录数
    String column = "UserID";//定义默认的查询列
%>

<%
    try{//如果没有输入参数那么就会是null,null无法变为数字
        currentPage = Integer.parseInt(request.getParameter("cp"));
    }catch(Exception e){}
    try{//如果没有输入参数那么就会是null,null无法变为数字
        lineSize = Integer.parseInt(request.getParameter("ls"));
    }catch(Exception e){}
    if(request.getParameter("kw")!=null){//表示有查询的关键字
        System.out.println("取得关键字:"+new String(request.getParameter("kw").getBytes("iso-8859-1"), "utf-8"));
        keyWord = new String(request.getParameter("kw").getBytes("iso-8859-1"), "utf-8");//将取得的关键字进行转换
    }
    if(request.getParameter("col")!=null){//表示有查询的检索列
        column = request.getParameter("col");
    }
    session.setAttribute("currentPage",currentPage);
    session.setAttribute("lineSize",lineSize);
    session.setAttribute("keyWord",keyWord);
    if (column.equals("UserID")) {
        session.setAttribute("column", "UserID");
    }else if (column.equals("UserName")){
        session.setAttribute("column", "UserName");
    }else {
        session.setAttribute("column", "UserStatus");
    }
%>
<%
    System.out.println("MStudentList.jsp页面接收到的参数!");
    System.out.println(currentPage);
    System.out.println(lineSize);
    System.out.println(keyWord);
    System.out.println(column);
%>
<script type="text/javascript">
    window.location = "MStudentList.action" ;
</script>
</body>
</html>

struts_MUserList.xml 负责处理请求

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <!-- 所有的Action定义都应该放在package下 -->
    <!-- 所有的Struts 2.x程序都要求设置命名空间 -->
    <!-- package中的name只是一个标识,你可以随意命名,其他的配置文件可以继承这个package.,package主要定义页面的可执行路径,如果设置为"/"(namespace="/"),则表示映射到根目录下,但是在配置文件里面有一些需要父配置文件的一些支持(例如:自动赋值与数据转换),所以extends继承一个父的配置文件(extends="struts-default") -->
    <package name="struts_MUserList" namespace="/"  extends="struts-default">
        <!--转入账户信息页面-->
        <action name="MStudentList" class="com.jluzh.action.MUserListAction">
            <result name="muserlist">/jsp/check/check.jsp</result>
        </action>
    </package>
</struts>

MUserListAction.java 处理请求的控制层

package com.jluzh.action;

import com.jluzh.service.factory.ServiceFactory;
import com.jluzh.vo.student;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jluzh on 2017/4/17.
 */
public class MUserListAction extends ActionSupport {
    private static final String TAG = "MUserListAction";
    private static final String MUSERLIST = "muserlist";// 执行跳转信息
    private Integer currentPage;// 当前页
    private Integer lineSize;// 每页多少数据
    private String keyWord;// 模糊查询的关键字
    private String column;// 模糊查询列

    @Override
    public String execute() throws Exception {
        System.out.println(TAG+":执行execute方法");
        String msg = "";//表示提示信息
        String url = "";//表示跳转路径
        // 1、使用ServletActionContext获取request对象。
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        //2.    取得路径后的字符串 *
        String status = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
        System.out.println("取得路径后的字符串:"+status);
        switch (status){
            case "MStudentList.action":
                System.out.println(TAG+":执行模糊查询学生用户的操作");
                keyWord = (String) session.getAttribute("keyWord");//取得页面传过来的查询账户
                column = (String) session.getAttribute("column");//取得页面传过来的查询列
                //        -- student(studentID, sStatus,studentID, studentName, studentPassword, sIdentity, sLastTime)
                System.out.println(column.equals("UserID"));
                if (column.equals("UserID")) {
                    column = "studentID";
                }else if (column.equals("UserName")){
                    column = "studentName";
                }else {
                    column = "sStatus";
                }
                lineSize = (Integer) session.getAttribute("lineSize");//取得页面传过来的查询每页多少数据
                currentPage = (Integer) session.getAttribute("currentPage");//取得页面传过来的查询当前页
                System.out.println("MUserListAction接收到的参数!");
                System.out.println(currentPage);
                System.out.println(lineSize);
                System.out.println(keyWord);
                System.out.println(column);
                if (keyWord != null && !keyWord.equals("")  && column != null && !column.equals("")){
                    if (ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord)>0){
                        System.out.println(TAG+":有模糊查询结果!");
                        session.setAttribute("allRecorders",ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord));//设置查询的数据量
                        session.setAttribute("lineSize",lineSize);//设置每页多少数据
                        session.setAttribute("currentPage",currentPage);//设置当前页
                        session.setAttribute("pageSize",ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord)/lineSize);//总共多少页
                        System.out.println(TAG+"设置allRecorders:"+ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord));
                        System.out.println(TAG+"设置pageSize:"+ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord)/lineSize);
                        //                创建一个List对象来接收查询结果
                        List<student> listByUser = new ArrayList<student>();
                        //执行查询并将结果反倒List集合中
                        listByUser =  ServiceFactory.getIStudentServiceInstance().findAllSplit(currentPage,lineSize,column,keyWord);
                        if (listByUser.size()>0){
                            //有查询结果,则将查询结果返回到页面
                            System.out.println(TAG+":模糊查询学生用户成功!");
                            request.setAttribute("msg","查询学生用户成功!");//提示信息
                            session.setAttribute("listByStudent",listByUser);
                            session.setAttribute("keyWord",keyWord);//保存查询的关键字
                            if (column.equals("studentID")) {
                                column = "UserID";
                                session.setAttribute("column",column);//保存查询的列
                            }else if (column.equals("studentName")){
                                column = "UserName";
                                session.setAttribute("column",column);//保存查询的列
                            }else {
                                column = "UserStatus";
                                session.setAttribute("column",column);//保存查询的列
                            }
                            request.setAttribute("url","/jsp/cdsp_information/manager/cdsp_studentManager.jsp");//增加学生成功后跳转到哪
                            return MUSERLIST;
                        }else{
                            ///无查询结果,则将错误信息返回到页面
                            System.out.println(TAG + ":模糊查询学生用户失败!");
                            session.setAttribute("QueryResult","模糊查询用户失败!");
                            request.setAttribute("msg", "模糊查询学生用户数据失败!");//提示信息
                            request.setAttribute("url", "/jsp/cdsp_information/manager/cdsp_studentManager.jsp");//增加学生失败后跳转到哪
                            return MUSERLIST;
                        }
                    }else{
                        session.setAttribute("allRecorders",ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord));//设置查询的数据量
                        session.setAttribute("pageSize",ServiceFactory.getIStudentServiceInstance().getAllCount(column,keyWord)/lineSize);//总共多少页
                        System.out.println(TAG+":无模糊查询结果!");
                        request.setAttribute("msg","无查询结果!!");
                        request.setAttribute("url","/jsp/cdsp_information/manager/cdsp_studentManager.jsp");
                        return MUSERLIST;
                    }
                }else if (keyWord == null && !keyWord.equals("")){
                    System.out.println(TAG+":关键字为空!!");
                    request.setAttribute("msg","关键字为空!!");
                    request.setAttribute("url","/jsp/cdsp_information/manager/cdsp_studentManager.jsp");
                    return MUSERLIST;                 
                }else {
                    System.out.println(TAG+":查询列为空!!");
                    request.setAttribute("msg","无关键字或查询列为空!!");
                    request.setAttribute("url","/jsp/cdsp_information/manager/cdsp_studentManager.jsp");
                    return MUSERLIST;

                }
            default:
                System.out.println(TAG+":路径字符串有问题!!");
                request.setAttribute("msg","路径字符串有问题!");
                request.setAttribute("url","/jsp/cdsp_information/manager/cdsp_studentManager.jsp");
                return MUSERLIST;
        }
    }
}

StudentDAOImpl.java DAO层

    /**
     * 进行列表的分页操作
     * @param currentPage 当前所在的页
     * @param lineSize 每页显示数据行数
     * @param column 要进行模糊查询的数据列
     * @param keyWord 模糊查询的关键字
     * @return
     * @throws SQLException
     */
    @Override
    public List<student> findAllSplit(Integer currentPage, Integer lineSize, String column, String keyWord) throws SQLException {
        //int allRecorders = 0;//保存总记录数
        //int pageSize = 0;//保存总页数
        System.out.println(TAG+"正在执行findAllSplit方法:数据的模糊查询");
        //编写一个接收查询数据的对象
        List<student> all = new ArrayList<student>();
//        -- student(studentID, sStatus,studentID, studentName, studentPassword, sIdentity, sLastTime)
//        1.创建执行书本模糊查询的SQL语句
        String sql =" SELECT studentID,sStatus,sIdentity,studentName,studentPassword,sLastTime " +
                " FROM student " +
                " WHERE "+ column +"  LIKE ? LIMIT ?,? ";
        System.out.println(sql);
//        select * from tablename limit 2,4
//        即取出第3条至第6条,4条记录
//        2.将SQL语句赋给执行对象
        this.pstmt = conn.prepareStatement(sql);
        this.pstmt.setString(1,"%"+keyWord+"%");// 模糊查询  %关键词%
        this.pstmt.setInt(2,(currentPage-1)*lineSize);//(当前所在的页 - 1) * 每页显示数据行数
        this.pstmt.setInt(3,lineSize);//每页最多显示数据行数
        //让对象执行查询,将结果放到ResultSet
        ResultSet rs = this.pstmt.executeQuery();
        //使用while进行查询
        while(rs.next()){
            //查询到了数据,将其添加到对象中
            //实例化一个接收数据的单个books对象
            student studentVo = new student();
            studentVo.setStudentID(rs.getString(1));//设置接收数据的对象的学生学号
            studentVo.setsStatus(rs.getInt(2));//设置接收数据的对象的学生状态
            studentVo.setsIdentity(rs.getString(3));//设置接收数据的对象的学生身份
            studentVo.setStudentName(rs.getString(4));//设置接收数据的对象的学生姓名
            studentVo.setStudentPassword(rs.getString(5));//设置接收数据的对象的学生密码
            studentVo.setsLastTime(rs.getTimestamp(6));//设置接收数据的对象的学生姓名
            //设置完参数后将该对象添加到List集合中
            all.add(studentVo);
        }
        System.out.println(TAG+"findAllSplit方法执行完成!");
        return all;//返回一个模糊查询到的所有数据的all集合
    }

    /**
     * 查询数据量
     * @param column 要进行模糊查询的数据列
     * @param keyWord 模糊查询的关键字
     * @return
     * @throws SQLException
     */
    @Override
    public Integer getAllCount(String column, String keyWord) throws SQLException {
        System.out.println(TAG+"正在执行getAllCount方法:模糊查询数据量的统计");
//        -- student(studentID, sStatus,studentID, studentName, studentPassword, sIdentity, sLastTime)
//        1.创建执行添加书本的SQL语句  column 要进行模糊查询的数据列
        String sql = " SELECT COUNT(*) FROM student WHERE "+column+" LIKE ? ";
//        2.将SQL语句设置给执行对象
        this.pstmt = conn.prepareStatement(sql);
//        3.给执行对象的SQL语句设置参数
        this.pstmt.setString(1,"%"+keyWord+"%");//设置查询的关键字
//        3.让执行对象执行SQL语句,并将结果返回到ResultSet中
        ResultSet rs = this.pstmt.executeQuery();
        if(rs.next()){
            System.out.println(TAG+"正在执行getAllCount方法:模糊查询数据量的统计-----------完成 有数据");
            return rs.getInt(1);//返回查询到的总记录数
        }
        System.out.println(TAG+"正在执行getAllCount方法:模糊查询数据量的统计-----------完成 数据为0");
        return 0;
    }
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值