【從零入門系列-5】Spring Boot 之 前端展現

文章系列


前言

前一章已經實現了對圖書管理經常使用的Web接口的功能服務,這一步將使用bootstrapbootstrap-table等前端技術整合後臺提供的服務功能完成一個圖書管理頁的功能設計,提供一個功能較爲完善的圖書館書籍管理功能頁。javascript

對於前端不熟的同窗能夠自行完成對bootstrap的學習,主要包括佈局、模態框、表格分頁、JQuery的學習,而後再回過頭來實踐本篇涉及內容。css


訪問頁設計實現

第一步咱們先創建好該頁面的路徑和結構,首先可以讓前端可以直接訪問到該頁面,因爲這裏的頁面內容爲Html頁面,非上一篇文章說起的Json內容,所以咱們須要區別對待。html

由於該頁面爲前端展現頁內容,咱們能夠把該接口單獨設計到另一個層-View層,即頁面展現層,該層提供對外訪問的頁面內容。可是,爲了項目簡單,並且這裏只有一個頁面,咱們在本項目中依然將該頁面接口放到控制層,代碼以下:前端

@RestController
@RequestMapping(path = "/library")
public class BookController {
    @Autowired
    private BookJpaRepository bookJpaRepository;

    @Autowired
    private BookService bookService;

    /**
     * 圖書管理頁
     * @return 返回圖書管理頁面內容
     */
    @RequestMapping(value = "")
    public ModelAndView index(){
        return new ModelAndView("index");
    }
    
    /* 其餘已有的代碼省略 */
}

在這裏,咱們使用@RequestMapping(value = "")關聯Web的訪問路徑,指定能夠接收任意類型(GET和POST等)的Web請求,且訪問路徑問/libraryjava

對應的該處理函數返回的類型爲ModelAndView,由於@RestController註解後類的接口返回的默認是Json類型,當咱們須要返回渲染的Html文件內容時,則須要使用ModelAndView了,上述代碼中返回的index是一個html文件,默認路徑爲項目路徑\src\main\resources\templates,所以咱們須要在templates目錄下新建一個index.html文件,文件內容以下:jquery

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>圖書館</title>
</head>
<body>

</body>
</html>

爲了測試頁面訪問路徑的通路,減小干擾項,目前這個頁面內容爲空,只設置了頁面標題名。git

而後咱們啓動程序,訪問地址http://localhost:8080/library就能夠發現能正常訪問到咱們這裏的index.html文件內容了。github

引入依賴的第三方組件

引入咱們的頁面即將要使用到bootstrapbootstrap-tablecssjs相關的文件,注意因爲bootstrap須要使用到jquery,因此咱們須要在引入bootstrap的JS前先將jquery引入,代碼內容以下:ajax

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>圖書館</title>
    <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap-table/1.14.2/bootstrap-table.css" rel="stylesheet">
</head>
<body>
    <!-- jQuery文件。務必在bootstrap.min.js 以前引入 -->
    <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <!-- bootstrap-table -->
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/bootstrap-table.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/locale/bootstrap-table-zh-CN.js"></script>
</body>
</html>

爲了偷懶,咱們這裏引入的第三方庫文件都是採用CDN的方式,也能夠選擇把庫下載到本地而後再引用。spring

注意到<html xmlns:th="http://www.thymeleaf.org">採用的是thymeleaf語法特性,並引入thymeleaf支持,相關thymeleaf知識能夠自行搜索學習,本項目基本不涉及thymeleaf知識點。

分頁表格數據展現

咱們項目使用b,若是你還沒使用過該組件,可參考此處學習,代碼以下:

<body>
    <!-- 表工具欄 -->
    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
    </div>

    <!-- 表結構 -->
    <div class="panel panel-default">
        <table id="book_table" >
            <!-- js實現表結構 -->
        </table>
    </div>

    <!-- jQuery文件。務必在bootstrap.min.js 以前引入 -->
    <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <!-- bootstrap-table -->
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/bootstrap-table.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/locale/bootstrap-table-zh-CN.js"></script>

    <!--兩種方法引用JS文件-->
    <!--1.原生引用-->
    <!-- <script src="/js/index.js"></script> -->
    <!--2.thymeleaf模版引用-->
    <script th:src="@{/js/comm.js}"></script>
    <script th:src="@{/js/index.js}"></script>
</body>

這裏須要新建兩個JS文件,其中index.js爲處理index.html頁面相關的JS內容,comm.js爲通用的JS相關代碼,因爲咱們按項目的默認配置引用文件,所以在static目錄下新建相對應的路徑便可:

  • index.js:項目路徑\src\main\resources\static\js\index.js
  • comm.js:項目路徑\src\main\resources\static\js\comm.js

bootstrap-table的使用主要在JS部分,在JS完成對錶格的配置及初始化,index.js相關代碼爲:

var $table;

//初始化bootstrap-table的內容
function InitMainTable () {
    //記錄頁面bootstrap-table全局變量$table,方便應用
    $table = $('#book_table').bootstrapTable({
        url: '/library/search',
        method: 'post',
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",
        toolbar: '#toolbar',
        dataType: "json",
        striped: true,                       // 設置爲 true 會有隔行變色效果
        undefinedText: "空",                 // 當數據爲 undefined 時顯示的字符
        pagination: true,                    // 分頁
        sortable: true,                      // 是否啓用排序
        sortOrder: "asc",                    // 排序方式
        sidePagination: "server",            // 分頁方式: client 客戶端分頁, server  服務端分頁(*)
        showPaginationSwitch:true,           // 是否顯示 數據條數選擇框
        showColumns: "true",                 // 是否顯示 內容列下拉框
        showRefresh: true,                   // 是否顯示刷新按鈕
        pageNumber: 1,                       // 若是設置了分頁,首頁頁碼
        pageSize: 3,                         // 若是設置了分頁,頁面數據條數
        pageList: [3, 5, 7],
        paginationPreText: '上一頁',         // 指定分頁條中上一頁按鈕的圖標或文字,這裏是<
        paginationNextText: '下一頁',        // 指定分頁條中下一頁按鈕的圖標或文字,這裏是>
        data_local: "zh-US",                 // 表格漢化
        clickToSelect: true,
        queryParams: function (params) {     // 獲得查詢的參數
            var param = getFormParam($('#formSearch'));
            // 頁大小
            param["pageSize"] =  params.limit;
            // 頁碼
            param["pageNumber"] =  (params.offset / params.limit);
            // 排序類型
            param["sortDir"] = params.order;
            // 排序字段
            param["ordName"] = params.sort;
            return param;
        },
        idField: "id",                       // 指定主鍵列
        columns: [
            {
                field: 'id',
                title: '書ID'
            }, {
                field: 'name',
                title: '書名'
            }, {
                field: 'author',
                title: '做者'
            },{
                field: 'image',
                title: '封面',
                formatter: function (value, row, index) {
                    return '<img src='+value+' alt="圖片加載失敗" >'
                }
            },{
                title: '操做',
                field: 'operate',
                align: 'center',
                formatter: operateFormatter,
                events: operateEvents
            }
        ]
    });
};

//操做欄的格式化
function operateFormatter(value, row, index) {
    var result = "";
    result += "<a type='button' id='cell_view'  data-toggle='modal' class='btn btn-xs yellow' title='查看'><span class='glyphicon glyphicon-search'></span></a>";
    result += "<a type='button' id='cell_edit'  data-toggle='modal' class='btn btn-xs yellow' title='編輯'><span class='glyphicon glyphicon-pencil'></span></a>";
    result += "<a type='button' id='cell_remove' data-toggle='modal' class='btn btn-xs blue' title='刪除'><span class='glyphicon glyphicon-remove'></span></a>";
    return result;
}

//指定table表體操做事件
window.operateEvents = {
    'click #cell_edit': function(e, value, row, index) {
    },
    'click #cell_view': function(e, value, row, index) {
    },
    'click #cell_remove': function(e, value, row, index) {
    }
};

// 頁面初始化
$(function(){
    InitMainTable();
    $table.bootstrapTable('refresh');
});

注意,表格數據源是咱們實現的Web搜索查詢接口/library/search,數據類型爲Json,請求方式:

method: 'post',
contentType:"application/x-www-form-urlencoded; charset=UTF-8",

其中獲取參數的函數封裝在comm.js文件中,代碼以下:

function getFormParam(form) {
    var param = {};
    form.find('[name]').each(function () {
        var value = $(this).val();
        if(value != '') {
            param[$(this).attr('name')] = value;
        }
    });
    return param;
}

此時運行程序訪問頁面咱們已經能夠看到頁面了,以下所示:

1557988091756

頁面已經出來了,能看到數據正常展現,並且也有分頁也生效了。

新增記錄

新增按鈕在表格的工具欄,設計成用戶點擊新增後彈框讓用戶輸入信息,完成書籍錄入。

在Html文件中,新增模態框內容部分,而後新增按鈕關聯模態框便可,Html代碼以下:

<div class="panel panel-default">
    <!-- 模態新增框 -->
    <div class="modal fade" id="modeAdd" tabindex="-1" role="dialog" aria-labelledby="modeAddTitle">
        <div class="tile modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
                    <h3 class="modal-title" id="modeAddTitle">添加書籍</h3>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="formAdd" method="post">
                        <div class="form-group row">
                            <label class="control-label col-md-3">書名</label>
                            <div class="col-md-8">
                                <input class="form-control" id="add_name" type="text" placeholder="請輸入書籍名稱" name="name" required>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="control-label col-md-3">做者</label>
                            <div class="col-md-8">
                                <input class="form-control" id="add_author" type="text" placeholder="請輸入做者名稱" name="author" required>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="control-label col-md-3">封面</label>
                            <div class="col-md-8">
                                <input class="form-control" id="add_image" type="text" placeholder="請輸入封面地址" name="image" required>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="onBtnAdd()">添加書籍</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 表工具欄 -->
    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal" data-target="#modeAdd">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
    </div>

    <!-- 表結構 -->
    <div class="panel panel-default">
        <table id="book_table" >
            <!-- js實現表結構 -->
        </table>
    </div>
</div>

在表工具欄部分,對新增按鈕新增屬性data-toggle="modal" data-target="#modeAdd"便可關聯新增模態框@modeAdd,此時運行程序在頁面點擊新增時,便可看到彈出的新增對話框。

此外,在用戶點擊添加書籍按鈕時綁定的處理函數是onBtnAdd(),咱們還須要在JS文件中新增該處理函數,內容以下:

function onBtnAdd() {
    var mod = $('#modeAdd');

    var para = getFormParam($('#formAdd'));

    $.ajax({
        type: "POST",
        url: "/book/save",
        data: para,
        success: function(data){
            if(!data.bid){
                alert('添加失敗' );
            }
            else {
                mod.modal('hide');
                $table.bootstrapTable('refresh');
                alert('添加成功');
            }
        },
        fail: function (e) {
            alert("執行異常," + e);
        }
    });
}

運行測試結果以下:

1557989641483

修改記錄

模態編輯框代碼:

<!-- 模態編輯框 -->
<div class="modal fade" id="modeEdit" tabindex="-1" role="dialog" aria-labelledby="modeEditTitle">
    <div class="tile modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
                <h3 class="modal-title" id="modeEditTitle">編輯書籍信息</h3>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="formEdit" method="post">
                    <div class="form-group row">
                        <label class="control-label col-md-3">書ID</label>
                        <div class="col-md-8">
                            <input  class="form-control" id="edit_id" type="text" placeholder="請輸入書籍ID" name="id" readonly>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="control-label col-md-3">書名</label>
                        <div class="col-md-8">
                            <input  class="form-control" id="edit_name" type="text" placeholder="請輸入書籍名稱" name="name" required>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="control-label col-md-3">做者</label>
                        <div class="col-md-8">
                            <input  class="form-control" id="edit_author" type="text" placeholder="請輸入做者名稱" name="author" required>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="control-label col-md-3">封面</label>
                        <div class="col-md-8">
                            <input class="form-control" id="edit_image" type="text" placeholder="請輸入封面地址" name="image" required>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="onBtnEdit()">肯定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
            </div>
        </div>
    </div>
</div>

operateEvents實現對編輯按鈕的響應,填入編輯數據並彈出模態框,肯定後經過提供的Web編輯接口完成數據更新,其相關JS代碼以下:

//指定table表體操做事件
window.operateEvents = {
    'click #cell_edit': function(e, value, row, index) {
        $('#edit_id').val(row['id']);
        $('#edit_name').val(row['name']);
        $('#edit_author').val(row['author']);
        $('#edit_image').val(row['image']);

        $('#modeEdit').modal('show');
    },
    'click #cell_view': function(e, value, row, index) {
    },
    'click #cell_remove': function(e, value, row, index) {
    }
};

// 編輯書籍
function onBtnEdit() {
    var mod = $('#modeEdit');
    var para = getFormParam($('#formEdit'));

    $.ajax({
        type: "POST",
        url: "/library/edit/" + para["id"],
        data: para,
        success: function(data){
            if(data["code"] != 0){
                alert('更新失敗' );
            }
            else {
                mod.modal('hide');
                $table.bootstrapTable('refresh');
                alert('更新成功');
            }
        },
        fail: function (e) {
            alert("執行異常," + e);
        }
    });
}

測試結果以下:

1557994746028

查看記錄

模態框代碼:

<!-- 模態查詢框 -->
<div class="modal fade" id="modeView" tabindex="-1" role="dialog" aria-labelledby="modeViewTitle">
    <div class="tile modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
                <h3 class="modal-title" id="modeViewTitle">查看書籍信息</h3>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="formView" method="post">
                    <div class="form-group row">
                        <label class="control-label col-md-2">書ID</label>
                        <div class="col-md-10">
                            <input  class="form-control" id="view_id" type="text" placeholder="請輸入書籍ID" name="id" readonly>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="control-label col-md-2">書名</label>
                        <div class="col-md-10">
                            <input  class="form-control" id="view_name" type="text" placeholder="請輸入書籍名稱" name="name" readonly>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="control-label col-md-2">做者</label>
                        <div class="col-md-10">
                            <input  class="form-control" id="view_author" type="text" placeholder="請輸入做者名稱" name="author" readonly>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="control-label col-md-2">封面</label>
                        <div class="col-md-10">
                            <input class="form-control" id="view_image" type="text" placeholder="請輸入封面地址" name="image" readonly>
                            <img class="form-control" id="view_image_show" alt="圖片顯示失敗" src="" style="width: auto; height: auto; max-width: 80%; max-height: 80%;"/>
                        </div>

                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">肯定</button>
            </div>
        </div>
    </div>
</div>

相關的JS處理代碼:

//指定table表體操做事件
window.operateEvents = {
    'click #cell_edit': function(e, value, row, index) {
        $('#edit_id').val(row['id']);
        $('#edit_name').val(row['name']);
        $('#edit_author').val(row['author']);
        $('#edit_image').val(row['image']);

        $('#modeEdit').modal('show');
    },
    'click #cell_view': function(e, value, row, index) {
        onBtnView(row["id"]);
    },
    'click #cell_remove': function(e, value, row, index) {
    }
};


// 查看書籍信息
function onBtnView(id){
    $.ajax({
        type: "GET",
        url: "/library/view/" + id,
        success: function(data){
            if(data["code"] != 0){
                alert('查詢失敗' );
            }
            else {
                var row = data["data"];
                $('#view_id').val(row['id']);
                $('#view_name').val(row['name']);
                $('#view_author').val(row['author']);
                $('#view_image').val(row['image']);
                $("#view_image_show").attr('src',row["image"]);
                $('#modeView').modal('show');
            }
        },
        fail: function (e) {
            alert("執行異常," + e);
        }
    });
}

運行測試結果:

1557995675042

刪除記錄

刪除時,彈出一個框提示用戶確認便可,所以只須要JS代碼,代碼以下:

//指定table表體操做事件
window.operateEvents = {
    'click #cell_edit': function(e, value, row, index) {
        $('#edit_id').val(row['id']);
        $('#edit_name').val(row['name']);
        $('#edit_author').val(row['author']);
        $('#edit_image').val(row['image']);

        $('#modeEdit').modal('show');
    },
    'click #cell_view': function(e, value, row, index) {
        onBtnView(row["id"]);
    },
    'click #cell_remove': function(e, value, row, index) {
        if(confirm("是否要刪除記錄[" + row["id"] + "-" + row["name"] + "] ?")) {
            onBtnRemove(row["id"]);
        }
    }
};

// 刪除書籍
function onBtnRemove(id) {
    $.ajax({
        type: "get",
        url: "/library/remove/" + id,
        success: function(data){
            $table.bootstrapTable('refresh');
            alert('刪除成功');
        },
        fail: function (e) {
            alert("刪除失敗," + e);
        }
    });
}

運行測試結果:

1557996076431

搜索查詢

提供搜索查詢功能,查詢頁面代碼以下:

<!-- 查詢面板 -->
<div class="panel panel-default">
    <div class="panel-heading">查詢條件</div>
    <div class="panel-body">
        <form id="formSearch" class="form-horizontal" method="get">
            <div class="form-group" style="margin-top:15px">
                <div class="col-sm-3">
                    <label class="control-label col-sm-4" for="txt_search_name">書名</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="name" id="txt_search_name">
                    </div>
                </div>

                <div class="col-sm-3">
                    <label class="control-label col-sm-4" for="txt_search_id" valign="center">書ID</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="id"  id="txt_search_id">
                    </div>
                </div>

                <div class="col-sm-3">
                    <label class="control-label col-sm-4" for="txt_author" valign="center">做者</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="author"  id="txt_author">
                    </div>
                </div>

                <div class="col-sm-3">
                    <button class="btn btn-round btn-primary" type="button" id="btn_query" onclick="onTableSearch()">查詢</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 表工具欄 -->
<div id="toolbar" class="btn-group">
    <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal" data-target="#modeAdd">
        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
    </button>
</div>

搜索處理JS的代碼以下:

// 查詢搜索
function onTableSearch(){
    $table.bootstrapTable('refresh');
};

搜索查詢結果測試:

1557997291641

結束語

到這裏,整個項目已經完成,已根據此前設計完成了書籍頁的管理,謝謝您的關注。

項目地址

相關文章
相關標籤/搜索