【ssm個人博客項目實戰(zhàn)05】easy ui datagrid實現(xiàn)數(shù)據(jù)的分頁顯示

目錄

【SpringBoot2.0文章匯總目錄,java多線程教程文章匯總 長期更新系列

請多多支持

前面一節(jié) 我們已經(jīng)實現(xiàn)博客類別的dao層的實現(xiàn),其中特別講解了博客類別的分頁的實現(xiàn),那么現(xiàn)在我們實現(xiàn)了后臺的分頁,那么前臺分頁怎么顯示呢,這時候我們用到了easyui的datagrid了。
先上一下效果圖

分頁結(jié)果

1、數(shù)據(jù)格式準(zhǔn)備工作

首先我們要知道datagrid解析的是什么樣的數(shù)據(jù)。在我們jquery-easyui-1.3.5/demo/datagrid/datagrid_data1.json

datagrid_data1.json

從圖中我們可以看出來
這是一個接送對象,其中
total:代表的是總記錄數(shù)目
rows:每條記錄的數(shù)組
這就意味著我們后臺返回的數(shù)據(jù)是一個json對象
里面有兩個字段分別是total跟rows
前面我們已經(jīng)在dao分別定義了并實現(xiàn)了如下方法

  /**
     * 分頁查詢博客類別信息
     * @param start
     * @param end
     * @return
     */
    List<BlogType> listByPage(@Param("start") Integer start, @Param("end") Integer end);

    /**
     * 查詢總記錄數(shù)
     * @return
     */
    Long getTotal();

那么只要我們把這個兩個方法查詢的數(shù)據(jù)json序列化返回跟前臺就可以了,到這里我們需要做一些業(yè)務(wù)處理,把一些業(yè)務(wù)邏輯方法service層里面。

2、業(yè)務(wù)層實現(xiàn)

由于分頁處理我們使用的字段很多例如
currPage:當(dāng)前頁數(shù)
pageSize:每頁顯示數(shù)目
total:總記錄數(shù)目
result:分頁查詢結(jié)果,
由于字段很多所以我們直接把它封裝成類PageBan 由于不僅僅是博客類別需要分頁 博客也要分頁 所以我們把這個PageBean設(shè)置為泛型
PageBean<T>

package ssm.blog.entity;

import java.util.List;

/**
 * Created by xp on 2017/4/14.
 */
public class PageBean<T> {

    private int currPage;   //當(dāng)前頁數(shù)
    private int pageSize;   //每頁顯示的個數(shù)
    private long total;      //總記錄數(shù)
    private int start;
    private int end;
    private List<T> result; //分頁查詢的結(jié)果

    PageBean(){

    }

    public PageBean(int currPage, int pageSize) {
        this.currPage = currPage;
        this.pageSize = pageSize;
        this.start = (currPage-1)*pageSize;
        this.end = currPage*pageSize;
    }

    public int getCurrPage() {
        return currPage;
    }

    public void setCurrPage(int currPage) {
        this.currPage = currPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<T> getResult() {
        return result;
    }

    public void setResult(List<T> result) {
        this.result = result;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getEnd() {
        return end;
    }

    public void setEnd(int end) {
        this.end = end;
    }

    @Override
    public String toString() {
        return "PageBean{" +
                "currPage=" + currPage +
                ", pageSize=" + pageSize +
                ", total=" + total +
                ", start=" + start +
                ", end=" + end +
                ", result=" + result +
                '}';
    }
}

其中我們在構(gòu)造方法public PageBean(int currPage, int pageSize)
中初始化了start 與end這樣我們下次直接get就可以了

新建接口 BlogTypeService

package ssm.blog.service;

import org.springframework.stereotype.Service;
import ssm.blog.entity.BlogType;
import ssm.blog.entity.PageBean;

/**
 * Created by xp on 2017/4/14.
 * @author xp
 * @Description 博客類別service接口
 */
public interface BlogTypeService {

    //分頁查詢
    PageBean<BlogType> listByPage(PageBean<BlogType> pageBean);

    
}

寫出對應(yīng)的實現(xiàn)類

package ssm.blog.service.impl;

import org.springframework.stereotype.Service;
import ssm.blog.dao.BlogTypeDao;
import ssm.blog.entity.BlogType;
import ssm.blog.entity.PageBean;
import ssm.blog.service.BlogTypeService;

import javax.annotation.Resource;

/**
 * Created by xp on 2017/4/14.
 * @author xp
 * @Description 博客類別service接口實現(xiàn)類
 */
@Service
public class BlogTypeServiceImpl implements BlogTypeService{

    @Resource
    private BlogTypeDao blogTypeDao;

    public PageBean<BlogType> listByPage(PageBean<BlogType> pageBean) {
        //查詢分頁結(jié)果
        pageBean.setResult(blogTypeDao.listByPage(pageBean.getStart(),pageBean.getEnd()));
        //查詢記錄總數(shù)
        pageBean.setTotal(blogTypeDao.getTotal());
        return pageBean;
    }
}

3、控制層實現(xiàn)

由于我們使用的datagrid 當(dāng)前我們點擊下一頁看看請求的參數(shù)

Paste_Image.png

從圖中可以看出來請求的有兩個參數(shù)
page:當(dāng)前頁數(shù)
rows:每頁顯示的數(shù)目

所以我們的控制器就要接受請求的參數(shù)
這樣我們就可以使用@RequestParam注解來接受前臺的傳來的參數(shù)
因為datagrid需要的是json數(shù)據(jù) 所以這里我們需要將 對象序列化
這里我使用的是阿里巴巴的fastjson
在pom添加相關(guān)依賴

 <!-- 阿里巴巴json序列化工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>

在ssm.blog.controller.admin包下新建BlogTypeController
具體的代碼如下

 package ssm.blog.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.RequestParam;
import ssm.blog.entity.BlogType;
import ssm.blog.entity.PageBean;
import ssm.blog.service.BlogService;
import ssm.blog.service.BlogTypeService;
import ssm.blog.util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
* Created by xp on 2017/4/14.
* @author xp
* @Description 博客分類控制器
*/
@Controller
@RequestMapping(value = "/admin/blogType")
public class BlogTypeController {

   @Resource
   private BlogTypeService blogTypeService;

   // 分頁查詢博客類別
   @RequestMapping("/list")
   public String listBlogType(
           @RequestParam(value = "page", required = false) String page,
           @RequestParam(value = "rows", required = false) String rows,
           HttpServletResponse response) throws Exception {
       //定義分頁bean
       PageBean<BlogType> pageBean = new PageBean<BlogType>(Integer.parseInt(page)
               ,Integer.parseInt(rows));
       //拿到分頁結(jié)果已經(jīng)記錄總數(shù)的pageBean
       pageBean = blogTypeService.listByPage(pageBean);
       //使用阿里巴巴的fastJson創(chuàng)建JSONObject
       JSONObject result = new JSONObject();
       //通過fastJson序列化list為jsonArray
       String jsonArray = JSON.toJSONString(pageBean.getResult());
       JSONArray array = JSONArray.parseArray(jsonArray);
       //將序列化結(jié)果放入json對象中
       result.put("rows", array);
       result.put("total", pageBean.getTotal());

       //使用自定義工具類向response中寫入數(shù)據(jù)
       ResponseUtil.write(response, result);
       return null;
   }
}

部分注解解釋

其中@Controller代表這是一個控制器bean
@RequestMapping(value = "/admin/blogType") 類級別的請求路徑 我們使用admin代表這是后臺管理blogType代表管理博客類別
@RequestMapping("/list")就是請求這個分頁方法的路徑

fastjson序列化

第一步 創(chuàng)建 JSONObject result = new JSONObject();
第二步 使用 JSON.toJSONString方法將List對象序列化成json字符串
第三步 將json字符串轉(zhuǎn)成JSONArray對象
第四步 將數(shù)據(jù)put進(jìn)result中
第五步 將result方法

如何將json返回

第一步獲取response對象
在SpringMVC中我們可以直接在方法形參中添加HttpServletResponse response即可
第二步拿到response的文本輸出流對象 既
PrintWriter pw = response.getWriter();
第三步將我們需要返回的json對象寫入response中
pw.println(obj.toString());
第四部關(guān)閉刷新輸出流并且關(guān)閉
pw.flush();
pw.close();
因為我們可能在其他的方法也需要返回json對象 所以我們將這個流程封裝成一個靜態(tài)方法放在工具類中

在ssm.blog.util包中新建ResponseUtil類
代碼如下

package ssm.blog.util;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by xp on 2017/4/14.
 */
public class ResponseUtil {
    /**
     * 向response對象寫入數(shù)據(jù)
     * @param response
     * @param obj
     * @throws Exception
     */
    public static void write(HttpServletResponse response, Object obj)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(obj.toString());
        out.flush();
        out.close();
    }
}

接下來我們可以測試后臺返回數(shù)據(jù)格式是否滿足我們的要求
在這里我們使用Postman測試 url

http://localhost:8080/admin/blogType/list.do?page=1&rows=5

結(jié)果如圖

請求結(jié)果

結(jié)果與前面datagrid_data1.json格式一致滿足我們的要求

4、前端視圖處理

在webapp目錄下面的admin目錄下面新建blogTypeManage.jsp

打開easyUI API手冊 搜索datagrid

datagrid

從圖中可以看出來datagrid本質(zhì)就是table
有兩種方法可以創(chuàng)建datagrid 在這里我們先使用js動態(tài)創(chuàng)建datagrid
先貼上代碼

<%--
  Created by IntelliJ IDEA.
  User: xp
  Date: 2017/4/14
  Time: 08:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html lang="en">
<head>
    <title>博客類別管理</title>
    <%@include file="../common/head.jspf" %>
</head>
<script>
    $(function () {
        //datagrid初始化
        $('#dg').datagrid({
            //請求數(shù)據(jù)的url
            url: '${blog}/admin/blogType/list.do',
            //載入提示信息
            loadMsg: 'loading...',
            //水平自動展開,如果設(shè)置此屬性,則不會有水平滾動條,演示凍結(jié)列時,該參數(shù)不要設(shè)置
            fitColumns: true,
            //數(shù)據(jù)多的時候不換行
            nowrap: true,
            //設(shè)置分頁
            pagination: true,
            //設(shè)置每頁顯示的記錄數(shù),默認(rèn)是10個
            pageSize: 5,
            //每頁顯示記錄數(shù)項目
            pageList: [5, 10, 15, 20],
            //指定id為標(biāo)識字段,在刪除,更新的時候有用,如果配置此字段,在翻頁時,換頁不會影響選中的項
            idField: 'id',
            //上方工具條 添加 修改 刪除 刷新按鈕
            toolbar:[{
                iconCls: 'icon-add',    //圖標(biāo)
                text: '添加',            //名稱
                handler: function () {  //回調(diào)函數(shù)
                    alert("添加");
                }
            },'-',{
                iconCls: 'icon-edit',
                text: '修改',
                handler: function () {
                      alert("添加");
                    }
            },'-',{
                iconCls: 'icon-edit',
                text: '刪除',
                handler: function () {
                      alert("刪除");
                }
            },'-',{
                iconCls: 'icon-reload',
                text: '刷新',
                handler: function () {
                     alert("刷新");
                }
            }],
            //同列屬性,但是這些列將會凍結(jié)在左側(cè),z大小不會改變,當(dāng)寬度大于250時,會顯示滾動條,但是凍結(jié)的列不在滾動條內(nèi)
            frozenColumns:[[
                {field:'checkbox',checkbox:true},    //復(fù)選框
                {field:'id',title:'編號',width:200}    //id字段
            ]],
            columns:[[
                {field:'typeName',title:'博客分類名稱',width:300},   //typeName 字段
                {field:'orderNum',title:'博客類別排序',width:300},   //orderNum 字段
            ]],
        });
    });
</script>
<body>
<table id="dg"></table>
</body>
</html>

從面上面代碼看出來我們只需聲明一個table接下我只需要通過js就能動態(tài)創(chuàng)建datagrid 代碼中的注解比較詳細(xì)我就不在多說了
接下來只需把我們的blogTypeManage.jsp與我們main.jsp關(guān)聯(lián)就可以

Paste_Image.png

這樣我們重啟tomcat 進(jìn)入主界面 在左側(cè)點擊博客類別管理
結(jié)果如圖


分頁結(jié)果

最后大家關(guān)注一下我的個人公眾號把。關(guān)注我公眾號即可獲取源碼


公眾號
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,778評論 18 399
  • 兩盞淡酒敬前塵,懷舊人,祭往恨。無人邀杯,唯有對孤燈。早歲無知卻輕狂,竟道是,莫無聞。酒罷微醺望星辰,半月沉,靜夜...
    Trumcy閱讀 539評論 0 3
  • 從小我就比較喜歡玩兒,而且是在別人看來特別會玩兒的那種。記得小時候特別喜歡做一些手工制作什么的,現(xiàn)在想起來對那...
    樊昀閱讀 597評論 0 1