layui的數據表格+springmvc實現數據顯示,分頁功能


在做分享圈項目后台時,用的是layui提供的后端頁面框架,頁面挺好看的。

下載layui包:組裝我們想要的頁面,layui在線示例       

看官方文檔api:數據表格   實現數據顯示,分頁功能。

①前端頁面:

要導入layui的layui.css和layui.js

<link rel="stylesheet" href="<%=request.getContextPath()%>/public/layui/src/css/layui.css">

<script src="<%=request.getContextPath()%>/public/layui/src/layui.js" charset="utf-8"></script>

html:

<table id="test" lay-filter="test"></table>

js操作:

<script>
    layui.use('table', function(){
        var table = layui.table;
 
        //渲染
        table.render({
            elem: '#test'  //綁定table表格
            ,height: 450
            ,url: '<%=request.getContextPath()%>/user/backContent' //后台springmvc接收路徑
            ,page:true    //true表示分頁
           /* page: { //支持傳入 laypage 組件的所有參數(某些參數除外,如:jump/elem) - 詳見文檔
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定義分頁布局
                //,curr: 5 //設定初始在第 5 頁
                ,groups: 3 //只顯示 1 個連續頁碼
                ,first: true //不顯示首頁
                ,last: true //不顯示尾頁
             }*/
//            ,where:{rows:limit} //傳參數
            ,limit: 10
            ,id:'contenttable'
            ,toolbar: '#toolbarDemo'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'id', width:80, fixed: 'left', unresize: true, sort: true}
                ,{field:'content', title:'內容', width:120, edit: 'text'}
                ,{field:'userid', title:'用戶id', width:80, edit: 'text', sort: true}
                ,{field:'nice', title:'點贊數', width:100}
                ,{field:'createtime', title:'分享時間', width:80, sort: true}
                ,{field:'pic1', title:'圖片1', width:120}
                ,{field:'pic2', title:'圖片2', width:100, sort: true}
                ,{field:'pic3', title:'圖片3', width:120}
 
            ]]
        });
 
 
 
        //監聽表格行點擊
        table.on('tr', function(obj){
            console.log(obj)
        });
 
        //監聽表格復選框選擇
        table.on('checkbox(test)', function(obj){
            console.log(obj)
        });
 
        //監聽表格單選框選擇
        table.on('radio(test2)', function(obj){
            console.log(obj)
        });
 
        //監聽單元格編輯
        table.on('edit(test2)', function(obj){
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有鍵值
                ,field = obj.field; //得到字段
 
        });
 
        //監聽工具條
        table.on('tool(test)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('真的刪除行么', function(index){
                    obj.del();
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                layer.prompt({
                    formType: 2
                    ,value: data.username
                }, function(value, index){
                    obj.update({
                        username: value
                    });
                    layer.close(index);
                });
            }
        });
 
        var $ = layui.jquery, active = {
            getCheckData: function(){//獲取選中數據
                var checkStatus = table.checkStatus('test')
                    ,data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
            ,getCheckLength: function(){//獲取選中數目
                var checkStatus = table.checkStatus('test')
                    ,data = checkStatus.data;
                layer.msg('選中了:'+ data.length + ' 個');
            }
            ,isAll: function(){驗證是否全選
                var checkStatus = table.checkStatus('test');
                layer.msg(checkStatus.isAll ? '全選': '未全選')
            }
            ,parseTable: function(){
                table.init('parse-table-demo', {
                    limit: 3
                });
            }
            ,add: function(){
                table.addRow('test')
            }
            ,delete: function(){
                layer.confirm('確認刪除嗎?', function(index){
                    table.deleteRow('test')
                    layer.close(index);
                });
            }
            ,reload:function () {
                var keyWord=$("#keyWord").val();
                var keyType=$("#key_type option:selected").val();
                table.reload('contenttable',{
                    where:{keyWord:keyWord,keyType:keyType}
                });
            }
        };
        $('i').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });
</script>

springmvc后台代碼:

controller層:

/**
 * layui-content后台代碼
 * @return
 */
@RequestMapping("/backContent")
@ResponseBody
public ResultMap<List<Content>> backContent(Page page,@RequestParam("limit") int limit){
    System.out.println("backContent========================"+limit);
    page.setRows(limit);
    System.out.println("page:"+page.toString());
    List<Content>contentList=contentService.selectPageList(page);
    int totals=contentService.selectPageCount(page);
    page.setTotalRecord(totals);
    return new ResultMap<List<Content>>("",contentList,0,totals);
}

因為layui的數據表格需要的格式json不只是一個數據數組,而是

{

code: 0,
msg: "",
count: 數據總記錄數,
data: []

}

需要參數code(要為0,不然數據表格數據顯示不出),msg(返回的消息),data(表格顯示的數據),totals(查詢到數據的總記錄數),

所以用ResultMap返回數據

/**
 * 
 * layui數據表格返回數據處理類
 * Created by ASUS on 2018/5/19
 *
 * @Authod Grey Wolf
 */
public class ResultMap<T> {
    private String msg;
    private  T data;
    private  int code;
    private  int count;
 
    public String getMsg() {
        return msg;
    }
 
    public void setMsg(String msg) {
        this.msg = msg;
    }
 
    public T getData() {
        return data;
    }
 
    public void setData(T data) {
        this.data = data;
    }
 
    public int getCode() {
        return code;
    }
 
    public void setCode(int code) {
        this.code = code;
    }
 
    public int getCount() {
        return count;
    }
 
    public void setCount(int count) {
        this.count = count;
    }
 
    public ResultMap(String msg, T data, int code, int count) {
        this.msg = msg;
        this.data = data;
        this.code = code;
        this.count = count;
    }
 
    public ResultMap() {
    }
}

Page類是我用來封裝分頁的數據的,比如layui的當前頁數,點擊下一頁的值。不用類封裝,也可以用springmvc的@RequestBody("page")int page 獲取layui傳到后台的當前頁數。

/**
 * 處理分頁
 * Created by ASUS on 2018/5/7
 *
 * @Authod Grey Wolf
 */
 
 
 
public class Page implements Serializable {
 
 
    //當前頁
    private Integer page=1;
    //頁大小
    private Integer rows=5;
    // 總記錄 數
    private Integer totalRecord;
    //總頁數
    private Integer totalPage;
    //關鍵字類型
    private String keyType;
    //查詢關鍵字
    private String keyWord;
    //開始記錄位置
    private Integer start;
    //用戶id
    private String userid;
    //其他用戶id
    private String otherid;
 
    public String getKeyType() {
        return keyType;
    }
 
    public void setKeyType(String keyType) {
        this.keyType = keyType;
    }
 
    public String getOtherid() {
        return otherid;
    }
 
    public void setOtherid(String otherid) {
        this.otherid = otherid;
    }
 
    public String getUserid() {
        return userid;
    }
 
    public void setUserid(String userid) {
        this.userid = userid;
    }
 
    public Integer getPage() {
        return page;
    }
 
    public void setPage(Integer page) {
        this.page = page;
    }
 
    public Integer getRows() {
        return rows;
    }
 
    public void setRows(Integer rows) {
        this.rows = rows;
    }
 
    public Integer getTotalRecord() {
        return totalRecord;
    }
 
    public void setTotalRecord(Integer totalRecord) {
        this.totalRecord = totalRecord;
    }
 
    public Integer getTotalPage() {
        totalPage=(totalRecord-1)/rows+1;
        return totalPage;
    }
 
    public void setTotalPage(Integer totalPage) {
 
        this.totalPage = totalPage;
    }
 
    public String getKeyWord() {
        return keyWord;
    }
 
    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }
 
    public Integer getStart() {
        start=(page-1)*rows;
        return start;
    }
 
    public void setStart(Integer start) {
 
        this.start = start;
    }
 
   
    public Page() {
    }
 
    public Page(Integer page, Integer rows, Integer totalRecord, Integer totalPage, String keyType, String keyWord, Integer start, String userid, String otherid) {
        this.page = page;
        this.rows = rows;
        this.totalRecord = totalRecord;
        this.totalPage = totalPage;
        this.keyType = keyType;
        this.keyWord = keyWord;
        this.start = start;
        this.userid = userid;
        this.otherid = otherid;
    }
 
    @Override
    public String toString() {
        return "Page{" +
                "page=" + page +
                ", rows=" + rows +
                ", totalRecord=" + totalRecord +
                ", totalPage=" + totalPage +
                ", keyType='" + keyType + '\'' +
                ", keyWord='" + keyWord + '\'' +
                ", start=" + start +
                ", userid='" + userid + '\'' +
                ", otherid='" + otherid + '\'' +
                '}';
    }
}

service層:

//分頁數據
    List<Content>selectPageList(Page page);
//分頁數據總數
    Integer selectPageCount(Page page);

serviceImpl層:

@Override
    public List<Content> selectPageList(Page  page) {
        List<Content>list=contentMapper.selectPageList(page);
        return list;
    }
 
    @Override
    public Integer selectPageCount(Page page) {
        return contentMapper.selectPageCount(page);
    }

mapper層:

    //通過關鍵字分頁查詢數據列表
    public List<Content> selectPageList(Page page);
 
    //通過關鍵字分頁查詢,返回總記錄數
    public Integer selectPageCount(Page page);

mapper.xml:

根據所傳來的參數,mapper執行相應的sql語句,返回結果集

<!-- 通過條件分頁查詢,返回數據集 -->
<select id="selectPageList" parameterType="net.stxy.one.model.Page" resultMap="BaseResultMap" >
  select
  <include refid="Base_Column_List" />
  from content
  <where>
    <if test="userid!=null and userid !=''">AND  userid = #{userid}</if>
    <if test="otherid!='' and otherid!=null">AND userid not in ( select DISTINCT  userid FROM  content where userid = #{otherid} )</if>
    <if test="keyWord!='' and keyType=='userid' ">
       AND userid like '%' #{keyWord} '%'
    </if>
    <if test="keyWord!='' and keyType=='content' ">
       AND content like '%' #{keyWord} '%'
    </if>
 
  </where>
  order by id DESC
  limit #{start},#{rows}
</select>
 
<!-- 通過條件分頁查詢,返回總記錄數 -->
<select id="selectPageCount" parameterType="net.stxy.one.model.Page"  resultType="java.lang.Integer">
  select count(1) from content
    <where>
      <if test="userid!=null and userid !=''">AND  userid = #{userid}</if>
      <if test="otherid!='' and otherid!=null">AND userid not in ( select DISTINCT  userid FROM  content where userid = #{otherid} )</if>
      <if test="keyWord!='' and keyType=='userid' ">
        AND userid like '%' #{keyWord} '%'
      </if>
      <if test="keyWord!='' and keyType=='content' ">
         AND content like '%' #{keyWord} '%'
      </if>
    </where>
</select>

總結下思路:前端點擊分享信息頁面,layui通過js代碼把獲取數據的請求url發到springmvc,springmvc根據傳來的參數,調用相應service層接口,操作數據訪問dao層,在mapper.xml執行相應的sql語句獲取到的結果集用list<>封裝起來,之后根據layui數據表格初始化需要的數據格式要求用ResultMap進行封裝數據,把數據傳回前端頁面。前端頁面根據傳回來的數據集合進行頁面渲染。點擊分頁按鈕的流程是一樣的,就是傳回后台的page改變了而已。

-----------------------------------------------------------------------------------------------------------------------------------------------感謝觀看!期待您的下次光臨!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM