spring-data-jpa + SpringBoot + bootstrapTable 後端分頁 模糊查詢

weixin_34253539發表於2017-08-22

spring-data-jpa + SpringBoot + bootstrapTable 後端分頁 模糊查詢

資料庫層ImageRepository 程式碼

package com.easy.kotlin.chapter11_kotlin_springboot.dao

import com.easy.kotlin.chapter11_kotlin_springboot.entity.Image
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param

/**
 * Created by jack on 2017/7/17.
 *
 *


@Query註解裡面的value和nativeQuery=true,意思是使用原生的sql查詢語句.
sql模糊查詢like語法,我們在寫sql的時候是這樣寫的

like '%?%'

但是在@Query的value字串中, 這樣寫

like %?1%

 */

interface ImageRepository : PagingAndSortingRepository<Image, Long> {
    @Query("SELECT a from #{#entityName} a where a.category like %?1%")
    fun findByCategory(category: String): MutableList<Image>

    @Query("select count(*) from #{#entityName} a where a.url = ?1")
    fun countByUrl(url: String): Int

    @Query("SELECT a from #{#entityName} a where a.category like %:searchText%")
    fun search(@Param("searchText") searchText: String, pageable: Pageable): Page<Image>
}

Controller 層

JSON 介面程式碼


    @RequestMapping(value = "wotuSearchJson", method = arrayOf(RequestMethod.GET))
    @ResponseBody
    fun wotuSearchJson(@RequestParam(value = "page", defaultValue = "0") page: Int,
                       @RequestParam(value = "size", defaultValue = "10") size: Int,
                       @RequestParam(value = "searchText", defaultValue = "") searchText: String): Page<Image>? {
        return getPageResult(page, size, searchText)
    }

    private fun getPageResult(page: Int, size: Int, searchText: String): Page<Image>? {
        val sort = Sort(Sort.Direction.DESC, "id")
        val pageable = PageRequest(page, size, sort)
        if(searchText==""){
            return imageRepository?.findAll(pageable)
        }else{
            return imageRepository?.search(searchText, pageable)
        }
    }

RequestMapping ModelAndView程式碼

    @RequestMapping(value = "meituView", method = arrayOf(RequestMethod.GET))
    fun meituView(): ModelAndView {
        return ModelAndView("meituView")
    }

檢視 meituView.ftl 程式碼

<#include 'head.ftl'>
<#include 'nav.ftl'>
<table id="meituTable"></table>
<#include 'foot.ftl'>

其中,

head.ftl

<!doctype html>
<html>
<head>
    <meta http-equiv=content-type content=text/html;charset=utf-8>
    <meta http-equiv=X-UA-Compatible content=IE=Edge>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>我圖</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="bower_components/bootstrap-table/src/bootstrap-table.css">
    <link href="app.css" rel="stylesheet">
</head>
<body>

需要注意的是,bootstrap-table與bootstrap 3是相容的。但是bootstrap 4還不行。

nav.ftl

<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">我圖</a>
        </div>
        <div>
            <ul class="nav navbar-nav">
                <li class="active"><a href="meituView">美圖列表</a></li>
                <li class=""><a href="doCraw" target="_blank">執行抓取</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        Kotlin極簡教程 <b class="caret"></b>
                    </a>
                    <ul class="dropdown-menu">
                        <li><a href="http://www.jianshu.com/nb/12976878" target="_blank">Kotlin</a></li>
                        <li><a href="#">SpringBoot</a></li>
                        <li><a href="#">Java</a></li>
                        <li class="divider"></li>
                        <li><a href="#">Scala</a></li>
                        <li class="divider"></li>
                        <li><a href="#">Groovy</a></li>
                    </ul>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">關於</a>
                </li>
            </ul>
            <#--<form class="navbar-form navbar-left" role="search">-->
                <#--<div class="form-group" id="search">-->
                    <#--<input type="text" class="form-control" placeholder="Search">-->
                <#--</div>-->
                <#--<button type="submit" class="btn btn-default">搜尋</button>-->
            <#--</form>-->
        </div>
    </div>
</nav>



foot.ftl

<script src="DataTables/media/js/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="bower_components/bootstrap-table/src/bootstrap-table.js"></script>
<script src="bower_components/bootstrap-table/src/locale/bootstrap-table-zh-CN.js"></script>
<script src="sloth.js"></script>
<script src="app.js"></script>
</body>
</html>

前端 app.js 程式碼

$(function () {

    var searchText = $('.search').find('input').val()

    var columns = [];
    columns.push({
        title: 'ID',
        field: '',
        align: 'center',
        valign: 'middle',
        formatter: function (value, row, index) {
            return row.id
        }
    });

    columns.push({
        title: '分類',
        field: 'category',
        align: 'center',
        valign: 'middle',
        formatter: function (value, row, index) {
            return value
        }
    }, {
        title: '美圖',
        field: 'url',
        align: 'center',
        valign: 'middle',
        formatter: function (value, row, index) {
            return "<a target='_blank' class='full-width' href='" + value + "'>![](" + value + ")</a>"
        }
    })

    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['zh-CN']);

    $('#meituTable').bootstrapTable({
        url: 'wotuSearchJson',
        sidePagination: "server",
        queryParamsType: 'page,size',
        contentType: "application/x-www-form-urlencoded",
        method: 'get',
        striped: false,     //是否顯示行間隔色
        cache: false,      //是否使用快取,預設為true,所以一般情況下需要設定一下這個屬性(*)
        pagination: true,  //是否顯示分頁(*)
        paginationLoop: true,
        paginationHAlign: 'right', //right, left
        paginationVAlign: 'bottom', //bottom, top, both
        paginationDetailHAlign: 'left', //right, left
        paginationPreText: ' 上一頁',
        paginationNextText: '下一頁',
        search: true,
        searchText : searchText,
        searchTimeOut: 500,
        searchAlign: 'right',
        searchOnEnterKey: false,
        trimOnSearch: true,
        sortable: true,    //是否啟用排序
        sortOrder: "desc",   //排序方式
        sortName: "id",
        pageNumber: 1,     //初始化載入第一頁,預設第一頁
        pageSize: 10,      //每頁的記錄行數(*)
        pageList: [5, 10, 20, 50, 100], // 可選的每頁資料
        totalField: 'totalPages',
        dataField: 'content', //後端 json 對應的表格資料 key
        columns: columns,
        queryParams: function (params) {
            return {
                size: params.pageSize,
                page: params.pageNumber,
                sortName: params.sortName,
                sortOrder: params.sortOrder,
                searchText: params.searchText
            }
        },
        classes: 'table table-responsive full-width',
    })


    $(document).on('keydown', function (event) {
        // 鍵盤翻頁事件
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode == 38 || e && e.keyCode == 37) {//上,左
            // 上一頁
            $('.page-pre').click()
        }
        if (e && e.keyCode == 40 || e && e.keyCode == 39) {//下,右
            // 下一頁
            $('.page-next').click()
        }

    })

})


其中,

$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['zh-CN']);

是 中文支援。

var searchText = $('.search').find('input').val() 這裡的$('.search').find('input') 

輸入框是bootstrapTable框架的搜尋輸入框。

完整工程原始碼:

https://github.com/EasyKotlin/chatper15_net_io_img_crawler

相關文章