BootStrap_實現分頁查詢【實例】

一、前言

    這個假期有點兒長,擼代碼有點兒手生了,就空餘時間總結一下這個很經典的BootStrap。計劃總結以下幾個部分:列表查詢、列表導出、列表導入。

  注:總結過程中使用的開發環境,開發工具,項目基礎結構如下: jdk1.8;tomcat7;maven3.5 ;idea;mysql;springboot;mybatis-plus。

二、背景

     我們以學生信息爲基礎,實現查詢學生信息,學生信息列表導出和學生信息列表導入三個功能。

三、數據庫建立

四、列表分頁查詢

4.1根據數據庫,建立開發此功能所需要的接口和類,這裏不重複敘述,不懂得可以看我初學Spring-boot系列的前幾篇文章。

    https://blog.csdn.net/weixin_40877388/category_9584708.html

4.2html頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>學生信息</title>
    <link rel="stylesheet" href="../static/common/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/common/bootstrap-table/bootstrap-table.css">
</head>
<body>
    <div class="wrapper wrapper-content animated fadeInRight"id="tablediv">
        <!--列表搜索條件-->
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>學生列表篩選條件</h5>
                        <!--<div class="ibox-tools">
                            <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                            <a class="close-link"><i class="fa fa-times"></i></a>
                        </div>-->
                    </div>
                    <div class="ibox-content search-query">
                        <div class="row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label class="control-label col-sm-2">學生id:</label>
                                    <div class="input-group col-sm-4">
                                        <input type="text" class="form-control" id="sId" name="sId">
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label class="control-label col-sm-2">學生學號:</label>
                                    <div class="input-group col-sm-4">
                                        <input type="text" class="form-control" id="sNumber" name="sNumber">
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label class="control-label col-sm-2">學生姓名:</label>
                                    <div class="input-group col-sm-4">
                                        <input type="text" class="form-control" id="sName" name="sName">
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label class="control-label col-sm-2">學生年齡:</label>
                                    <div class="input-group col-sm-4">
                                        <input type="text" class="form-control" id="sAge" name="sAge">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--<div class="hr-line-dashed"></div>-->
                    <div class="ibox-content search-query">
                        <div class="row">
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <button class="btn btn-primary infoSearchSubmit" type="button" id="studentSearchSubmit">
                                        搜索
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--列表內容-->
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h2>學生信息列表</h2>
                    </div>
                    <div class="alarm">
                        <button class="btn btn-danger" id="export" onclick="exportData()">導出Excle</button>
                        <button class="btn btn-danger" id="import" onclick="importData()">批量導入</button>
                    </div>

                    <div class="ibox-content">
                        <div class="row row-lg">
                            <div class="col-sm-12">
                                <div class="example-wrap">
                                    <div class="example" >
                                        <table id="studentTable"></table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <script src="../static/common/jquery-3.2.0.min.js"></script>
    <script src="../static/common/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <script src="../static/common/bootstrap-table/bootstrap-table.js"></script>
    <script src="../static/common/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
    <script src="../static/student_detail.js"></script>
</body>
</html>

4.3 student_detail.js

    關於bootstarp-table的解釋

function initExplainTable() {
    $('#explainTable').bootstrapTable({
        url: ctp + '/system/explain/selectPage',// controller方法的路徑
        method: 'post',// 請求方式 post 請求
        striped: true,// 是否顯示行間隔色 true  隔行變色
        cache: false,//是否使用緩存,默認爲true,所以一般情況下需要設置一下這個屬性(*)false  禁用ajax數據緩存
        pagination: true,// 表格底部顯示分頁條
        sortable: false,// 是否啓用排序  false 不排列
        sortOrder: "asc",// 自定義排序方式  asc 升序
        sidePagination: 'server',//,//分頁方式:client客戶端分頁,server服務端分頁(*)
        queryParamsType: 'limit',// 設置爲 'limit' 則會發送符合 RESTFul 格式的參數。
        queryParams: defaultQueryParams,//傳遞參數
        pageNumber: 1,// 初始化加載第一頁 默認第一頁
        pageSize: 10,// 每頁的記錄行數(*)
        pageList: [10, 50, 100],// 可供選擇的每頁的行數(*)
        clickToSelect: true,//是否啓用點擊選中行 true 啓用點擊選中行
        uniqueId: 'id',//每一行的唯一標識 一般爲主鍵列
        showRefresh: true,//是否顯示刷新按鈕 true 顯示刷新按鈕
        checkboxHeader: true,
        undefinedText: "-",//未定義文本
        search: true,//是否顯示錶格搜索,此搜索是客戶端搜索,不會進服務端,嚴格搜索
        searchOnEnterKey: true,
        searchTimeOut: 30,
        strictSearch: true,//true 嚴格搜索
        showColumns: true,//是否顯示所有的列 true 顯示所有的列
        height: 500, //行高,如果沒有設置height屬性,表格自動根據記錄條數覺得表格高度
        showToggle: true,//true 顯示詳細視圖和列表視圖的切換按鈕
        showPaginationSwitch: true,//true 顯示頁面切換
        minimumCountColumns: 2, //最少允許的列數
        toolbar: '#toolbar',//樣式
        idField: 'id',//指定主鍵列
        columns: [{
            field: 'explainName',//列字段名
            title: '說明名稱'     //頁面上展示的列名
        }, {
            field: 'explainValue',
            title: '說明內容'
        },{
            title: '操作',
            class: 'td-manage',
            formatter: function (value, row, index) {
                var editBtn = '';
                var delBtn = '';

                editBtn += '<a class="edit m-l-sm text-warning" title="編輯">';
                editBtn += '<i class="glyphicon glyphicon-edit"></i></a>';

                delBtn += '<a class="remove m-l-sm text-danger" title="刪除">';
                delBtn += '<i class="glyphicon glyphicon-remove"></i></a>';

                return editBtn + delBtn;
            }
        }]
    });
}

    我的代碼:

$(function(){

    initProjectTable();

})


//初始化學生列表
function initProjectTable(){
    //初始化列表
    $('#studentTable').bootstrapTable({
        url:  'getAllStudents',
        method: 'post',
        contentType:'application/x-www-form-urlencoded; charset=UTF-8',
        striped: true,
        cache: false,
        pagination: true,
        sortable: false,
        sortOrder: "asc",
        queryParamsType: 'limit',
        queryParams: defaultQueryParams,
        sidePagination: 'server',
        pageNumber: 1,
        pageSize: 5,
        pageList: [5,10, 50],
        clickToSelect: true,
        uniqueId: 'sId',
        showRefresh: true,
        checkboxHeader: true,
        undefinedText: "-",
        strictSearch: true,
        showColumns: true,
        showToggle: true,
        showPaginationSwitch: true,
        toolbar: '#toolbar',
        columns: [{
            field: 'sId',
            title: '學生id'
        },{
            field: 'sNumber',
            title: '學生編號'
        },{
            field: 'sName',
            title: '學生姓名'
        },{
            field: 'sAge',
            title: '學生年齡'
        }, {
            field: 'sId',
            title: '操作',
            class: 'td-manage',
            formatter: function (value, row, index) {
                var editBtn = '';
                var delBtn = '';
                editBtn += ' <button class="edit btn btn-primary btn-sm"  data-toggle="modal" data-target=".bs-example-modal-lg" title="編輯">編輯</button> ';
                delBtn += ' <button class="remove btn btn-danger btn-sm" title="刪除">刪除</button> ';

                return editBtn + delBtn;
            }
        }]
    });
}

//表格自定義參數
function defaultQueryParams(params) {
    params.pageNumber= this.pageNumber;//當前頁碼
    params.limit = this.pageSize;//查多少條(每頁顯示數量)
    //params.offset=(this.pageNumber-1)*this.pageSize;//sql語句起始索引
    return params;
}

4.4我的服務端分頁代碼

    4.4.1 Controller(PageHelper這個工具類我在4.4.5貼出)

package com.xuexue.firstproject.Controllers;



import com.xuexue.firstproject.Beans.Student;
import com.xuexue.firstproject.Services.IStudentService;
import com.xuexue.firstproject.common.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    IStudentService iStudentService;

    //訪問學生列表頁面
    @RequestMapping("/toStudent")
    public String toExport(){
        return "student_detail";
    }

    //查詢學生信息列表
    @RequestMapping(value = "/getAllStudents",method = RequestMethod.POST)
    @ResponseBody
    public PageHelper<Student> getAllStudents(Student student, Integer pageNumber, Integer limit){
        //System.out.println("offset:"+pageNumber+"limit:"+limit);
        return iStudentService.getAllStudents(student,pageNumber,limit);
    }

}

    4.4.2 Service

    接口:

package com.xuexue.firstproject.Services;

import com.baomidou.mybatisplus.service.IService;
import com.xuexue.firstproject.Beans.Student;
import com.xuexue.firstproject.common.PageHelper;


public interface IStudentService extends IService<Student> {

    //查詢學生信息列表
    PageHelper<Student> getAllStudents(Student student,Integer pageNumber, Integer limit);
}

    實現:

package com.xuexue.firstproject.Services.imp;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xuexue.firstproject.Beans.Student;
import com.xuexue.firstproject.Daos.StudentMapper;
import com.xuexue.firstproject.Services.IStudentService;
import com.xuexue.firstproject.common.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class StudentService  extends ServiceImpl<StudentMapper,Student> implements IStudentService {

    @Autowired
    StudentMapper studentMapper;

    //查詢學生信息列表
    @Override
    public PageHelper<Student> getAllStudents(Student student,Integer pageNumber, Integer limit) {
        //實例化一個用於儲存查詢回來的對象、信息的類
        PageHelper<Student> pageHelper = new PageHelper();
        //實例化mybatisplus條件構造器,拼接分頁查詢的條件
        Wrapper<Student> wrapper = new EntityWrapper<>();
        //根據條件查詢學生數量
        int total = studentMapper.selectCount(wrapper);
        //System.out.println(total);
        pageHelper.setTotal(total);
        //判斷學生數量,如果大於0,進行分頁查詢,如果小於0,返回空的list集合
        if(total>0){
            //分頁查詢;如果分頁limit不等於null,且大於0,說明是分頁查詢,否則是全部查詢
            if(limit != null && limit > 0){
                //實例化mybatis-plus分頁工具類
                Pagination pagination = new Pagination(pageNumber,limit);
                //分頁查詢學生信息
                pageHelper.setRows(studentMapper.selectPage(pagination,wrapper));
            }else{
                //查詢學生信息
                pageHelper.setRows(studentMapper.selectList(wrapper));
            }
        }else{
            //返回空的list集合
            pageHelper.setRows(new ArrayList<Student>());
        }
        return pageHelper;
    }
}

    4.4.3 Dao && Mapper

package com.xuexue.firstproject.Daos;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.xuexue.firstproject.Beans.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper extends BaseMapper<Student> {

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xuexue.firstproject.Daos.StudentMapper">
	
	<resultMap id="LxJobInfo" type="com.xuexue.firstproject.Beans.Student" >
		<result column="s_id" property="sId" />
		<result column="s_number" property="sNumber" />
	    <result column="s_name" property="sName" />
	    <result column="s_age" property="sAge" />
	</resultMap>

	<sql id="Base_Column_List">
		t.s_id,
		t.s_number,
		t.s_name,
		t.s_age
	</sql>

</mapper>

    4.4.4 Bean

package com.xuexue.firstproject.Beans;

import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;

import java.io.Serializable;

@TableName("student")
public class Student extends Model<Student> {

    @TableId(value = "s_id", type = IdType.AUTO)
    private Integer sId;
    private String sNumber;
    private String sName;
    private String sAge;

    public Integer getsId() {
        return sId;
    }

    public void setsId(Integer sId) {
        this.sId = sId;
    }

    public String getsNumber() {
        return sNumber;
    }

    public void setsNumber(String sNumber) {
        this.sNumber = sNumber;
    }

    public String getsName() {
        return sName;
    }

    public void setsName(String sName) {
        this.sName = sName;
    }

    public String getsAge() {
        return sAge;
    }

    public void setsAge(String sAge) {
        this.sAge = sAge;
    }

    @Override
    protected Serializable pkVal() {
        return this.sId;
    }
}

    4.4.5 返回數據工具類

package com.xuexue.firstproject.common;

import java.util.ArrayList;
import java.util.List;

public class PageHelper<T> {
    //實體類集合
    private List<T> rows = new ArrayList<T>();
    //數據總條數
    private int total;
    //字符串
    private String str;
    //對象
    private Object obj;
    
    public PageHelper() {
        super();
    }
 
    public List<T> getRows() {
        return rows;
    }
 
    public void setRows(List<T> rows) {
        this.rows = rows;
    }
 
    public int getTotal() {
        return total;
    }
 
    public void setTotal(int total) {
        this.total = total;
    }

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}
    
}

    至此,整個分頁查詢的例子就寫好了。

    但是這個例子中沒有寫按照條件查詢,如果想要按照條件查詢,需要將參數傳入後臺,並在分頁部分的代碼

Wrapper<Student> wrapper = new EntityWrapper<>();拼接條件就可以做到啦!

    詳細的寫法可以參考mybatis-plus官方文檔。https://mp.baomidou.com/

    如果沒有用mybatis-plus,也可以在mapper.xml文件中進行拼接。下面是個小例子

<select id="selectDesignerNoGroup"
            parameterType="com.**.**.dto.GroupMemberQuery"
            resultType="com.**.**.model.CustomerExtInfo">
        select
        bcei.id AS id ,
        bcei.customer_id as customerId,
        bcei.user_name as userName ,
        bcei.user_phone as userPhone,
        bcei.user_post as userPost
        from baishi_customer_ext_info bcei
        <where>
            and bcei.user_state = 0
            and bcei.customer_id not in (select group_owner_id from group_info where group_state = 0 )
            and bcei.customer_id not in (select member_id from group_member_info where member_state = 0 )
            and bcei.user_post = 2
            <!-- 地區areaId -->
            <if test="areaId != null and areaId !=''">
                AND bcei.area_id = #{areaId}
            </if>

            <!-- 名稱userName -->
            <if test="userName != null and userName !=''">
                AND bcei.user_name = #{userName}
            </if>

            <!-- 電話 -->
            <if test="userPhone != null and userPhone !=''">
                AND bcei.user_phone = #{userPhone}
            </if>
        </where>
    </select>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章