bootstrap-table的refresh查询

bootstrap-table具体用法不赘述了,详情参考这篇blog:
https://www.cnblogs.com/laowangc/p/8875526.html
查看好几篇refresh刷新的文章,但是没实现想要的功能:用post方法,在服务端分页,自定义查询条件。
特此,记录下。
本文章refresh查询主要参考这两篇:
Bootstrap Table 查询实现
bootstrapTable refresh 方法使用简单举例
主要说明的是,查询用是refreshOptions,可以自定义查询条件,而用refresh只能刷新初始化时在queryParams设置好的参数,没法修改,但都可以修改url。
效果如下:
bootstrap-table的refresh查询
html定义

<div class="container" id="tableFileDiv">
        <div class="pull-right" style="padding-bottom: 10px;">
            <input placeholder="文件名" id="tableFileName" type="text" class="form-control" style="float:left;width:150px;margin-right:5px;">
            <input placeholder="文件组别" id="tableFileGroup" type="text" class="form-control" style="float:left;width:150px;margin-right:5px;">
            <select class="form-control" id="tableFileType" style="float:left;width:150px;margin-right:5px;">
                <option value="">文件类型</option>
                <option value="0">图片</option>
                <option value="1">pdf</option>
                <option value="2">excel</option>
                <option value="3">word</option>
                <option value="4">ppt</option>
                <option value="5">压缩文件</option>
                <option value="6">其他</option>
            </select>
            <input placeholder="文件描述" id="tableFileDesc" type="text" class="form-control" style="float:left;width:150px;margin-right:5px;">
            <input placeholder="文件创建开始时间" id="tableFileStartTime" type="text" class="form-control" style="float:left;width:150px;margin-right:5px;">
            <input placeholder="文件创建结束时间" id="tableFileEndTime" type="text" class="form-control" style="float:left;width:150px;margin-right:5px;">
            <div class="btn-group">
                <button id="btn-tableSearch" type="button" class="btn btn-primary btn-space">
                    <span class="fa fa-search" aria-hidden="true" >查询</span>
                </button>
                <button id="btn-tableReset" type="button" class="btn btn-warning">
                    <span class="fa fa-eraser" aria-hidden="true" >重置</span>
                </button>
            </div>
        </div>

        <table id="tableFile" class="table table-bordered table-hover table-striped"></table>
    </div>

js
首先jquery用InitBootstrapTable初始化bootstrap-table,其中queryParams参数,在使用refresh用到。
然后点击搜索按钮,tableFindFileCond使用freshOptions,调用自定义参数,刷新数据。

function InitBootstrapTable(){
    var oTableInit = new Object();
    oTableInit.Init = function(){
        var queryUrl = '/tableShow'

        $('#tableFile').bootstrapTable({
            url: queryUrl,                      //请求后台的URL(*)
            method: 'post',                      //请求方式(*)
            contentType: 'application/x-www-form-urlencoded',
            toolbar: '#toolbar',              //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
            pagination: true,                   //是否显示分页(*)
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
            pageNumber: 1,                      //初始化加载第一页,默认第一页,并记录
            pageSize: 10,                     //每页的记录行数(*)
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数(*)
            search: false,                      //是否显示表格搜索
            strictSearch: false,
            showColumns: false,                  //是否显示所有的列(选择显示的列)
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            //height: 500,                      //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
            uniqueId: "id",                     //每一行的唯一标识,一般为主键列
            showToggle: false,                   //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                  //是否显示父子表
            silent: true,
            //得到查询的参数
            queryParams : function(params){
                //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                    sort: params.sort,                          //排序列名
                    sortOrder: params.sortOrder,                 //排序命令(desc, asc)
                };
                return temp;
            },
            columns: [{
                field: 'fileName',
                title: '文件名',
                sortable: true
            },{
                field: 'fileType',
                title: '文件类型',
                sortable: true,
                formatter: function(value, row, index){
                    var ftype = ["图片","pdf","excel","word","ppt","压缩文件","其他"]
                    var typeName = ftype[5]

                    if(value != null && value != ""){
                        typeName = ftype[parseInt(value)]
                    }
                    return typeName
                }
            },{
                field: 'fileMD5',
                title: '文件MD5',
                sortable: true
            },{
                field: 'fileGroup',
                title: '文件组别',
                sortable: true
            },{
                field: 'description',
                title: '文件描述',
                sortable: true
            },{
                field: 'size',
                title: '文件大小',
                sortable: true,
                formatter: function showSize(fsize, row, index){
                    var fsizeName = ''
                    if(fsize < 1024){
                        fsizeName = fsize + 'B'
                    }else if(fsize < 1024 * 1024){
                        fsizeName = (fsize / 1024.0).toFixed(2) + 'KB'
                    }else {
                        fsizeName = (fsize / 1024.0 / 1024.0).toFixed(2) + 'MB'
                    }
                    return fsizeName
                }
            },{
                field: 'createTime',
                title: '文件创建时间',
                sortable: true
            },{
                field: 'updateTime',
                title: '文件修改时间',
                sortable: true
            },{
                title: '操作',
                align: 'center',
                formatter: function operation(value, row, index){
                    var d = '<button  class="btn btn-success" οnclick="readyDownloadFile(`' + row.fileUrl + '`,`' + row.fileName + '`)"' +
                            ' data-url=' + row.fileUrl + ' data-name=' + row.fileName +
                            '><i class="fa fa-download"></i></button>'
                    return d
                }
            }],
            formatNoMatches: function(){
                return "没有相关的匹配结果"
            },
            onClickRow: function(row, $element){
                //$element.css("background-color", "green");
            },
            locale: "zh-CN",
            onl oadSuccess: function(){
            },
            onl oadError: function(){
                alert("数据加载失败")
            }
        })
    }
    return oTableInit;
}
$("#btn-tableReset").on("click", function(){
    $('#tableFileName').val("")
    $('#tableFileType').val("")
    $('#tableFileGroup').val("")
    $('#tableFileDesc').val("")
    $('#tableFileStartTime').val("")
    $('#tableFileEndTime').val("")
})

$("#btn-tableSearch").on("click", function(){
    tableFindFileCond()
})

function tableFindFileCond(){
    var name = $('#tableFileName').val()
    var type = $('#tableFileType').val()
    var group = $('#tableFileGroup').val()
    var desc = $('#tableFileDesc').val()
    var startTime = $('#tableFileStartTime').val()
    var endTime = $('#tableFileEndTime').val()

    if(startTime != ""){
        startTime = startTime.replace("年", "-")
        startTime = startTime.replace("月", "-")
        startTime = startTime.replace("日", "")
    }
    if(endTime != ""){
        endTime = endTime.replace("年", "-")
        endTime = endTime.replace("月", "-")
        endTime = endTime.replace("日", "")
    }

    if(name == "" && type == "" && group == "" && desc == ""
        && startTime == "" && endTime == ""){
        alert("查询内容为空,请输入查询内容")
        return ""
    }

    if((startTime == "" && endTime != "") ||
       (startTime != "" && endTime == "")){
        alert("查询时间时,开始或者结束时间不能为空,请输入查询时间段")
        return ""
    }

    //这部分没起作用
    var opt = {
        url: '/tablefind',
        silent: true,
        queryParams:{
            filename: name,
            filegroup: group,
            filetype: type,
            filedesc: desc,
            filestarttime: startTime,
            fileendtime: endTime,
        }
    }
    //refresh刷新初始化的参数
    //refreshOptions,初始化设置的选项
    //$("#tableFile").bootstrapTable('refresh', opt);
    $("#tableFile").bootstrapTable('refreshOptions', {
        url: '/tablefind',
        silent: true,
        queryParams: function(params){
            var temp = {
                filename: name,
                filegroup: group,
                filetype: type,
                filedesc: desc,
                filestarttime: startTime,
                fileendtime: endTime,
                rows: params.limit,
                page: (params.offset / params.limit)
            }
            return temp
        }
    });
}

服务端springboot
必须返回rows和total两个参数,不然分页显示不正常
用request.getParameter获取参数

//初始化刷新显示所有的页面
@RequestMapping(value="/tableShow", method = RequestMethod.POST)
    @ResponseBody
    public String showFileToTable(HttpServletRequest request, HttpServletResponse response){        
        int totalSize = plantFileService.findCount();
        String rows = request.getParameter("rows");
        String page = request.getParameter("page");
        List<UpFileEntity> fileEntities = (List<UpFileEntity>) plantFileService.findPage(Integer.parseInt(rows), Integer.parseInt(page) - 1);
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONStringWithDateFormat(fileEntities, "yyyy-MM-dd HH:mm:ss"));
        JSONObject ob = new JSONObject();
        ob.put("rows", jsonArray);
        ob.put("total", totalSize);
        return ob.toString();
    }
 
//搜索显示结果   
@RequestMapping(value = "/tablefind")
    @ResponseBody
    public String showTableFindFile(HttpServletRequest request, HttpServletResponse response){
        JSONObject respJsonObject = new JSONObject();

        String findFileName = request.getParameter("filename");
        String findFileGroup = request.getParameter("filegroup");
        String findFileType = request.getParameter("filetype");
        String findFileDesc = request.getParameter("filedesc");
        String findFileStartTime = request.getParameter("filestarttime");
        if(findFileStartTime.isEmpty() == false){
            findFileStartTime += " 00:00:00";
        }
        String findFileEndTime = request.getParameter("fileendtime");
        if(findFileEndTime.isEmpty() == false){
            findFileEndTime += " 00:00:00";
        }

        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp timestamp;
        String sTime = "";
        String eTime = "";
        Date dateTime;
        if(findFileStartTime.isEmpty() == false){
            timestamp = Timestamp.valueOf(findFileStartTime);
            sTime = format.format(timestamp);
        }
        if(findFileEndTime.isEmpty() == false){
            timestamp = Timestamp.valueOf(findFileEndTime);
            eTime = format.format(timestamp);
        }

        try{
            int rows = Integer.parseInt(request.getParameter("rows"));
            int page = Integer.parseInt(request.getParameter("page"));

            List<UpFileEntity> svrFile = null;
            String sqlPre = "select * from booklib where is_delete <> 1 and ";
            String sql = "";
            String sqlTemp = "";

            if(findFileName.isEmpty() == false){
                //svrFile = (List<UpFileEntity>)plantFileService.findAllByFileName(condName);
                sqlTemp = " file_name like '%" + findFileName + "%'";
                sql += sqlTemp;
            }
            if(findFileStartTime.isEmpty() == false && findFileEndTime.isEmpty() == false){               
                sqlTemp = " create_time >= '" + sTime + "' and create_time <= '" + eTime + "'";
                if(sql.isEmpty()){
                    sql += sqlTemp;
                }else{
                    sql += " and " + sqlTemp;
                }
            }
            if(findFileType.isEmpty() == false){
                sqlTemp = " file_type like '%" + findFileType + "%'";
                if(sql.isEmpty()){
                    sql += sqlTemp;
                }else{
                    sql += " and " + sqlTemp;
                }
            }
            if(findFileGroup.isEmpty() == false){
                sqlTemp = " file_group like ’%" + findFileGroup + "%'";
                if(sql.isEmpty()){
                    sql += sqlTemp;
                }else{
                    sql += " and " + sqlTemp;
                }
            }
            if(findFileDesc.isEmpty() == false){
                sqlTemp = " description like '%" + findFileDesc + "%'";
                if(sql.isEmpty()){
                    sql += sqlTemp;
                }else{
                    sql += " and " + sqlTemp;
                }
            }
            //分页查询
            String sqlLast= " order by id limit " + rows + " offset " + rows * page;
            String sqlFileMax = "select count(*) from booklib where is_delete <> 1 and ";
            sqlFileMax += sql;
            sql = sqlPre + sql + sqlLast;
            Integer pageMax = plantFileService.queryAllByCondGetCount(sqlFileMax);

            svrFile = (List<UpFileEntity>) plantFileService.queryAllByCond(sql);

            JSONArray jsonArray = JSON.parseArray(JSON.toJSONStringWithDateFormat(svrFile, "yyyy-MM-dd HH:mm:ss"));
            JSONObject ob = new JSONObject();
            ob.put("rows", jsonArray);
            ob.put("total", pageMax);
            return ob.toString();

        }catch (Exception e){
            respJsonObject.put("message", "查询失败" + e.getMessage());
            respJsonObject.put("status", false);
            respJsonObject.put("rows", JSONArray.parseObject(""));
            respJsonObject.put("total", 0);
        }
        return String.valueOf(respJsonObject);
    }
上一篇:WPF使用RawInput接收裸数据


下一篇:spiring系列-看源码AbstractApplicationContext.refresh()->finishBeanFactoryInitialization()