SpringBoot+FreeMarker+Bootstrap+JDBC實現增刪改查以及分頁

附上源碼地址源碼地址,點擊"源碼地址"前往github查看

一、創建SpringBoot項目

1)File->New->Project

新建項目

2)創建Spring Initializr以及選擇JDK版本

選擇項目工具以及JDK版本

3)填寫項目信息

填寫項目信息

4)選擇web依賴包---Spring Web Starter或者Web,具體根據頁面顯示的勾選

選擇web依賴包

5)選擇項目保存路徑

項目保存路徑

6)創建項目成功,看一下目前的項目結構

項目目錄

二、設計數據庫

1)創建數據庫

  • 使用終端進入mysql
// "cd"到"mysql"目錄下
$ cd /usr/local/mysql
// 進入"mysql"
$ mysql -u root -p
// 輸入密碼
Enter password: 
// 密碼驗證成功,則進入"mysql"
mysql> 
  • 創建數據庫
// 創建數據庫"js_springboot_demo"
create database js_springboot_demo character set utf8;
// 查看數據庫
show databases;
創建數據庫

2)創建數據表

// 進入我們的數據庫`js_springboot_demo`
use js_springboot_demo
// 創建數據表
create table user (id int(11) auto_increment primary key, title varchar(255) not null, name varchar(255) null, wx_number varchar(255) null);
// 查看表
show tables;
// 查看表的詳細信息
describe user;
創建表

3)連接數據庫

  • idea打開項目,選擇右側database
連接數據庫1
  • 選擇mysql
連接數據庫2
  • mysql數據庫信息填寫
連接數據庫3

連接數據庫4
  • 連接成功后,再次回到database,可以看到我們創建的數據庫以及表、字段等信息
連接數據庫5

三、添加項目依賴庫以及相關配置

1)添加依賴庫

打開pom.xml文件,依次添加下列依賴庫:

  • 添加FreeMarker
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  • 添加數據庫(mysqljdbc
<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  • 添加Gson
<dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
</dependency>
  • 添加lombok插件,用于生成gettersetter方法(需要先在idea設置中添加該插件再進行依賴庫的引入)

a、添加lombok插件

安裝lombok插件

b、添加依賴庫

<dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
</dependency>

2)配置

打開application.properties文件,添加如下配置:

#本地數據庫
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/js_springboot_demo
spring.datasource.username=root
spring.datasource.password=****

spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

server.port=8080
server.connection-timeout=10s
server.tomcat.uri-encoding=UTF-8

#freemarker 配置信息
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
#設定ftl文件路徑
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.expose-spring-macro-helpers=false
#設定靜態文件路徑,js,css等
spring.resources.static-locations=classpath:/templates/,classpath:/static/

四、測試Java Class與前端.ftl頁面的連接

1)view(即前端.ftl頁面)

  • templates中創建一個名為user的目錄,且在該目錄下創建一個名為index.ftl文件
創建.ftl頁面
  • index.ftl內容
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>測試</title>
</head>
<body>
<!-- ${name}為freemarker的模板 -->
<p>hello world!!! ${name} </p>

</body>
</html>

2)Controller(即java class

  • 創建一個名為HelloWorldControllerjava class
controller
  • 實現
package com.springboot.helloworld.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@RestController
public class HelloWorldController {
    @GetMapping("/index")
    public ModelAndView index(Map<String, Object> map){

        map.put("name", "af");
        return new ModelAndView("user/index", map);
    }
}
  • 頁面展示

打開瀏覽器,訪問http://localhost:8080/index

頁面展示

如上,可以通過controller訪問頁面后,接下來我們進行本章重點內容:增刪改查以及分頁的介紹

五、實現增刪改查功能

這里我們先介紹一下java的層級結構,主要分為以下四層:
dao層:主要跟數據庫進行交互,稱為持久層一般是創建一個dao接口,然后去定義接口的實現類。
entity層:數據庫在項目中的類,稱為實體層或者model層主要就是去定義與數據庫中的對象相對應的屬性,包括gettersettertoString方法以及一些構造函數等。
service層:控制業務的,稱為業務層主要負責業務模塊的邏輯應用設計,也是先設計接口,然后去定義接口的實現類。其實就是將業務邏輯獨立出來,有利于復用。
controller層:管理業務以及頁面跳轉,稱為控制層主要獲取前端數據,調用service方法,轉發到下一個頁面等

1)entity

  • 創建實體包

右擊helloworld,選擇New->Package,命名為entity

創建實體包

  • 創建實體類

右擊entity,選擇New->Java Class,命名為UserEntity,并添加如表user中的屬性(數據表中字段常以_分割,java class中常以駝峰命名,對應關系詳解可以查看這篇文章

package com.springboot.helloworld.entity;

import lombok.Data;
//@Data: lombok,生成getter、setter方法
@Data
public class UserEntity {
//    id
    private int id;
//    標題
    private String title;
//    姓名
    private String name;
//    微信
    private String wxNumber;
}

2)dao

  • 同創建實體包一樣,創建一個名為dao的包
  • dao下創建一個名為UserDao的接口

接口創建

UserDao接口中添加如下方法:

package com.springboot.helloworld.dao;

import com.springboot.helloworld.entity.UserEntity;

import java.util.List;

public interface UserDao {
    /***
     * 查詢用戶
     * @return
     */
    public List<UserEntity> selectUser(String keyword);
    /**
     * 插入數據
     */
    public int insertUser(UserEntity user);

    /**
     * 刪除數據
     */
    public int deleteUser(int uid);

    /**
     * 更新數據
     */
    public int updateUser(UserEntity user);
}

  • UserDao接口添加實現類,名為UserDaoImpl,并實現接口UserDao的方法
package com.springboot.helloworld.dao.impl;

import com.springboot.helloworld.dao.UserDao;
import com.springboot.helloworld.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<UserEntity> selectUser(String keyword) {
        String sql = "SELECT * FROM user WHERE CONCAT(id, title, name, wx_number) LIKE ?";
        return jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%"}, new BeanPropertyRowMapper<>(UserEntity.class));
}

    @Override
    public int insertUser(UserEntity user) {
        String sql = "INSERT INTO user(title, name, wx_number) VALUES(?, ?, ?)";

        return jdbcTemplate.update(sql, user.getTitle(), user.getName(), user.getWxNumber());
    }

    @Override
    public int updateUser(UserEntity user) {
        String sql = "UPDATE user SET title=?, name=?, wx_number=? WHERE id=?";

        return jdbcTemplate.update(sql, user.getTitle(), user.getName(), user.getWxNumber(), user.getId());
    }

    @Override
    public int deleteUser(int uid) {
        String sql = "DELETE FROM user WHERE id=?";
        return jdbcTemplate.update(sql, uid);
    }
}

3)service

  • 同創建實體包一樣,創建一個名為service的包
  • service下創建一個名為UserService的接口

UserService接口中添加如下方法:

package com.springboot.helloworld.service;

import com.springboot.helloworld.entity.UserEntity;

import java.util.Map;

public interface UserService {
    //    查詢
    public Map<String, Object> selectUser(String keyword);
    //    插入
    public String insertUser(UserEntity user);
    //    刪除
    public String deleteUser(String uid);
    //    更新
    public String updateUser(UserEntity user);
}
  • UserService接口添加實現類,名為UserServiceImpl,并實現接口UserService的方法
package com.springboot.helloworld.service.impl;

import com.google.gson.JsonObject;
import com.springboot.helloworld.dao.UserDao;
import com.springboot.helloworld.entity.UserEntity;
import com.springboot.helloworld.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Map<String, Object> selectUser(String keyword) {
        List<UserEntity> list = userDao.selectUser(keyword);
        Map<String, Object> map = new HashMap<>();
        if (list.size() == 0){
            map.put("userList", list);
            map.put("message", "沒有查詢到數據");
        }else{
            map.put("userList", list);
        }
        return map;
    }

    @Override
    public String insertUser(UserEntity user) {
        JsonObject result = new JsonObject();
        if (user.getName().isEmpty()) {
            result.addProperty("code", "-1");
            result.addProperty("message", "標題不能為空");
        }else{
            int insertResult = userDao.insertUser(user);
            if (insertResult >= 1){
                result.addProperty("code", "200");
                result.addProperty("message", "插入成功");
            }else{
                result.addProperty("code", "0");
                result.addProperty("message", "插入失敗");
            }
        }
        return result.toString();
    }

    @Override
    public String updateUser(UserEntity user) {

        JsonObject result = new JsonObject();
        int updateResult = userDao.updateUser(user);
        if (updateResult >= 1){
            result.addProperty("code", "200");
            result.addProperty("message", "修改成功");
        }else{
            result.addProperty("code", "0");
            result.addProperty("message", "修改失敗");
        }

        return result.toString();
    }

    @Override
    public String deleteUser(String uid) {
        int deleteResult = userDao.deleteUser(Integer.parseInt(uid));

        JsonObject result = new JsonObject();
        if (deleteResult >= 1){
            result.addProperty("code", "200");
            result.addProperty("message", "刪除成功");
        }else{
            result.addProperty("code", "0");
            result.addProperty("message", "刪除失敗");
        }
        return result.toString();
    }
}

4)web

在測試連接的部分我們已經創建了index.ftl頁面了,這里就不再重復創建了。

  • 插入

要實現的效果:先在頁面上添加一個插入按鈕,點擊插入彈出模態框,輸入對應信息,然后在頁面上顯示插入結果
代碼

/**
 * html代碼 
 **/
<button type="button" class="btn btn-primary" style="float: left;margin:20px 20px 0;" data-toggle="modal" data-target="#infoModel" data-id="insertCommit">插入</button>
<div class="modal fade" id="infoModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="recipient-title" class="col-form-label">標題:</label>
                        <input type="text" class="form-control" id="recipient-title" name="title">
                    </div>
                    <div class="form-group">
                        <label for="recipient-name" class="col-form-label">名稱:</label>
                        <input type="text" class="form-control" id="recipient-name" name="name">
                    </div>
                    <div class="form-group">
                        <label for="recipient-wxnum" class="col-form-label">微信號:</label>
                        <input type="text" class="form-control" id="recipient-wxnum" name="wxNumber">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="commitBtn" onclick="commitEvent(this)">提交</button>
            </div>
        </div>
    </div>
</div>
<p id="requestResult">請求結果:</p>

/**
 * jQuery代碼 
 **/
//顯示模態視圖
$('#infoModel').on('show.bs.modal', function (event) {
    // $("#commitBtn").attr("data-id", "insertEvent");

});

//模態視圖提交內容
commitEvent = function (event) {
    // console.log($(event).attr("data-id"));
    insertEvent();
};

//    插入
insertEvent = function () {
    //將form表單內容轉為json串
    var jsonStr = JSON.stringify($('form').serializeJSON());
    console.log(jsonStr);
//    通過ajax請求接口
    $.ajax({
        type: "POST",
        url: "/insertUser",
        contentType: "application/json",//數據請求格式
        dataType : 'json',//數據返回格式
        data: jsonStr,
        success: function(result){
            console.log(result);
            $('#requestResult').append('success===' + result);
            $('#infoModel').modal('hide');
            //插入成功后刷新頁面
            //window.location.reload();
        },
        error:function(error){
            console.log(error);
            $('#requestResult').append('error===' + error);
            $('#infoModel').modal('hide');
        }
    });
}
  • 查找全部

要實現的效果:用列表形式展示查詢到的所有數據
代碼

/**
 * html
**/
<#--數據展示-->
<div class="table-responsive">
    <table class="table">
        <thead>
        <tr>
            <th scope="col" style="width: 10%;"> ID </th>
            <th scope="col" style="width: 30%;">標題</th>
            <th scope="col" style="width: 20%;">姓名</th>
            <th scope="col" style="width: 20%;">微信</th>
            <th scope="col" style="width: 20%;">操作</th>
        </tr>
        </thead>
        <tbody>
        <#if userList?? && (userList?size > 0)>
            <#list userList as row>
                <tr>
                    <th scope="row">${row.id}</th>
                    <td>${row.title}</td>
                    <td>${row.name}</td>
                    <td>${row.wxNumber}</td>
<!-- 修改和刪除的按鈕先放著,事件會在后續代碼中進行說明 -->                
                    <td>
                      <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#infoModel" data-id="alterCommit" data-param='{"id":"${row.id}","title":"${row.title}","name":"${row.name}","wxNumber":"${row.wxNumber}"}'>修改</button>
                      <button class="btn btn-danger" onclick="deleteRow(${row.id})">刪除</button>
                  </td>
                </tr>
            </#list>

        <#else>
            <p>${message}</p>
        </#if>
        </tbody>
    </table>
</div>
  • 更新

查找全部的前端頁面中,已經加入了修改刪除按鈕,這里就只寫相關事件了(注:修改同樣是要彈出模態視圖,跟插入共用一個,不同之處是修改的時候需要給form表單賦值,那么插入則需要將form表單的值清空):

//顯示模態視圖
$('#infoModel').on('show.bs.modal', function (event) {
    //獲取當前點擊按鈕,用于判斷是插入還是修改
    var button = $(event.relatedTarget);
    var btnId = button.data('id');
    //用于填充表單
    var modal = $(this);

    if (btnId == "insertCommit"){
        //插入
        modal.find("#recipient-title").val("");
        modal.find("#recipient-name").val("");
        modal.find("#recipient-wxnum").val("");

    } else if (btnId == "alterCommit"){
    //    修改
        var info = button.data("param");
        console.log(info);

        modal.find("#recipient-title").val(info.title);
        modal.find("#recipient-name").val(info.name);
        modal.find("#recipient-wxnum").val(info.wxNumber);

        //傳rowid用于修改數據
        $("#commitBtn").attr("data-rowId", info.id);
    }

    //提交按鈕加上id用于區分是插入提交還是修改提交
    $("#commitBtn").attr("data-id", btnId);
});

//模態視圖提交內容
commitEvent = function (event) {
    var btnId = $(event).attr("data-id");
    if (btnId == "insertCommit") {
        insertEvent();
    }else if (btnId == "alterCommit"){
        var rowId = $(event).attr("data-rowId");
        updateEvent(rowId);
    }

};
//    修改
updateEvent = function (rowId) {
    var object = $('form').serializeJSON();
    var paramInfo = {
        "title": object.title,
        "name" : object.name,
        "wxNumber" : object.wxNumber,
        "id": rowId
    }
    var jsonStr = JSON.stringify(paramInfo);
    console.log(jsonStr);

    $.ajax({
        type: "POST",
        url: "/updateUser",
        contentType: "application/json",
        dataType: "json",
        data: jsonStr,
        success: function(result){
            console.log(result);
            var json = JSON.parse(result);
            //    關閉模態框
            $('#infoModel').modal('hide');
            //刷新頁面
            window.location.reload();

        },
        error:function(result){
            alert("error");
            $('#infoModel').modal('hide');
        }
    });
}
  • 關鍵字搜索

要實現的效果:在搜索框中輸入內容,查找數據庫中所有包含該內容的數據并展示
代碼

/**
 * html
**/
<div class="input-group mb-3" style="width: 90%;margin: 20px 0 0 20px;float: left;">
    <input type="text" class="form-control" id="search_id" placeholder="請輸入關鍵字" aria-label="關鍵字" aria-describedby="basic-addon2">
    <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="button" type="submit"  onclick="searchId()">搜索</button>
    </div>
</div>
/**
 * jQuery
**/
//    搜索
searchId = function () {
    var keyword = $("#search_id").val();
    window.location.href = "/index?keyword=" + keyword;
}
  • 刪除
//    刪除
deleteRow = function (rowId) {
    var param = {
        "uid": rowId,
    }
    var jsonStr = JSON.stringify(param);
    $.ajax({
        type: "POST",
        url: "/deleteUser",
        contentType: "application/json",
        dataType: "json",
        data: jsonStr,
        success: function(result){
            console.log(result);
            //刷新頁面
            window.location.reload();
        },
        error:function(result){
            alert("error");
        }
    });
}

5)controller

在測試連接的部分我們已經創建了HelloWorldController頁面了,這里就不再重復創建了。

在開始Controller之前,有個知識點需要提一下。在這個項目中,我們使用@RequestBody注解來使Spring自動將http中的body(json格式)轉換為java內部的類。該項目中我們使用了Gson,但由于Spring內部默認使用JackSon來進行轉換,所以我們需要配置一下。

  • 配置Gson

創建:
創建一個名為GsonHttpMessageConverterConfiguration的類:

Gson配置

配置:

package com.springboot.helloworld.config;

import com.google.gson.Gson;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;

@Configuration
@ConditionalOnClass(Gson.class)
@ConditionalOnMissingClass("com.fasterxml.jackson.core.JsonGenerator")
@ConditionalOnBean(Gson.class)
public class GsonHttpMessageConverterConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(gson);
        return converter;
    }
}

HelloworldApplication啟動類中加入不適用JackSon的代碼:

@SpringBootApplication (
//        確保Jackson沒有被使用
        exclude = {
                JacksonAutoConfiguration.class,
        }
)

有了以上配置,我們就可以使用Gson中的JsonObject來接收前端傳過來的json串了。

  • 插入
//    插入
@PostMapping(value = "/insertUser", consumes="application/json")
public String insert(@RequestBody JsonObject object){
    UserEntity user = new Gson().fromJson(object, UserEntity.class);
    return userService.insertUser(user);
}
  • 查找/關鍵字搜索

由于需要將查詢結果顯示在index頁面上,即訪問http://localhost:8080/index展示查詢結果,所以HelloWorldController中查詢就寫在上面測試連接的方法中:

//默認keyword為空串,即查找全部
@GetMapping(value = "/index")
public ModelAndView index(@RequestParam(value = "keyword", defaultValue = "") String keyword){
    return new ModelAndView("user/index", userService.selectUser(keyword));
}
  • 更新
//    修改
@PostMapping(value = "/updateUser", consumes = "application/json")
public String update(@RequestBody JsonObject object){
    UserEntity user = new Gson().fromJson(object, UserEntity.class);
    return userService.updateUser(user);
}
  • 刪除
//    刪除
@PostMapping(value = "/deleteUser", consumes = "application/json")
public String delete(@RequestBody JsonObject object){
    String userId = object.get("uid").toString();
    return userService.deleteUser(userId);
}

到這里為止,我們的增刪改查功能已經全部實現,接下來我們看分頁的實現。

六、實現分頁功能

主要實現分頁從數據庫中查詢記錄,包括加入關鍵字搜索的分頁查詢。

1) 添加PageEntity實體類

entity包下添加分頁的實體類,并實現構造方法計算總頁數等數據。
PageEntity實體類的實現

package com.springboot.helloworld.entity;

import lombok.Data;

import java.util.List;

@Data
public class PageEntity {
    /**
     * 當前頁碼
     */
    private int currentPage;
    /**
     * 每頁顯示條數
     */
    private int pageSize;
    /**
     * 數據庫查詢到的記錄總條數
     */
    private int totalRecordSize;
    /**
     * 當前頁的數據列表
     */
    private List<UserEntity> currentRecordList;
    /**
     * 關鍵字
     */
    private String keyword;


    /**
     * 總頁數
     */
    private int totalPage;
    /**
     * 頁碼開始索引
     */
    private int startPageIndex;
    /**
     * 頁碼結束索引
     */
    private int endPageIndex;


//    構造方法
    public PageEntity(int currentPage, int pageSize, String keyword, int totalRecordSize, List<UserEntity> recordList){
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.keyword = keyword;
        this.totalRecordSize = totalRecordSize;
        this.currentRecordList = recordList;

        /**
         * 計算總頁數
         */
        totalPage = (totalRecordSize + pageSize - 1) / pageSize;
        /**
         * 計算beginPageIndex以及endPageIndex
         * 如果是10頁以內,則頁數為1~10
         * 大于10頁,則顯示10附近的10個頁數,比如6~15、7~16......
         */
        if (totalPage <= 10){
            startPageIndex = 1;
            endPageIndex = totalPage;
        }else{
//            前4頁+當前頁+后5頁
            startPageIndex = currentPage - 4;
            endPageIndex = currentPage + 5;
//            當前面頁數不足4頁時,顯示前10個頁面
            if (startPageIndex < 1){
                startPageIndex = 1;
                endPageIndex = 10;
            }
//            當后面頁數不足5頁時,顯示后面10個頁碼
            if (endPageIndex > totalPage){
                startPageIndex = totalPage - 10 + 1;
                endPageIndex = totalPage;
            }
        }

    }
}

2) 在UserDao中添加分頁查詢接口,并在UserDaoImpl中實現該接口方法

UserDao實現代碼:

/**
 * 分頁查詢
 */
public PageEntity selectPageUser(int start, int size, String keyword);

UserDaoImpl實現代碼:

@Override
public PageEntity selectPageUser(int start, int size, String keyword) {
//         查詢記錄列表
    String sql = "SELECT * FROM user WHERE CONCAT(id, title, name, wx_number) LIKE ? LIMIT ?,?";
//        查詢總記錄數
    String recordSql = "SELECT COUNT(id) FROM user WHERE CONCAT(id, title, name, wx_number) LIKE ?";

    List<UserEntity> list = jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%", (start-1)*size, size}, new BeanPropertyRowMapper<>(UserEntity.class));
    int count = jdbcTemplate.queryForObject(recordSql, new Object[]{"%" + keyword + "%"}, Integer.class);
    return new PageEntity(start, size, keyword, count, list);
}

3) 在UserService中添加分頁查詢接口,并在UserServiceImpl中實現該接口方法

UserService實現代碼:

//    分頁
public Map<String, Object> selectPageUser(int start, int size, String keyword);

UserServiceImpl實現代碼:

@Override
public Map<String, Object> selectPageUser(int start, int size, String keyword) {
        PageEntity pageEntity = userDao.selectPageUser(start, size, keyword);
        List<UserEntity> list = pageEntity.getCurrentRecordList();
        Map<String, Object> map = new HashMap<>();
        map.put("userList", list);
        map.put("currentPage", pageEntity.getCurrentPage());
        map.put("totalPage", pageEntity.getTotalPage());
        map.put("keyword", pageEntity.getKeyword());
        map.put("pageUrl", "/index?");
        if (list.size() == 0){
            map.put("message", "暫時沒有數據哦");
        }
        return map;
}

4) 在HelloWorldController中,修改index方法

@GetMapping(value = "/index")
public ModelAndView index(@RequestParam(value = "keyword", defaultValue = "") String keyword, @RequestParam(value = "page", defaultValue = "1") Integer page){
    return new ModelAndView("user/index", userService.selectPageUser(page, 5, keyword));
}

5) 在index.ftl頁面中加入分頁

<#if userList?? && (userList?size > 0)>
<#--分頁-->
<div class="col-md-12 column">
    <ul class="pagination">
    <#--lte  less than or equal 小于等于-->
        <#if currentPage lte 1>
            <li class="disabled">
                <a class="page-link" href="#"><<</a>
            </li>
        <#else>
            <li>
                <a class="page-link" href="${pageUrl}page=${currentPage - 1}&keyword=${keyword}"><<</a>
            </li>
        </#if>

        <#list 1..totalPage as index>
            <#if currentPage == index>
                <li class="page-item active">
                    <a class="page-link" href="#">${index}</a>
                </li>
            <#else>
                <li>
                    <a class="page-link" href="${pageUrl}page=${index}&keyword=${keyword}">${index}</a>
                </li>
            </#if>
        </#list>
    <#--gte  greater than or equal  大于等于-->
        <#if currentPage gte totalPage>
            <li class="disabled">
                <a class="page-link" href="#">>></a>
            </li>
        <#else>
            <li>
                <a class="page-link" href="${pageUrl}page=${currentPage + 1}&keyword=${keyword}">>></a>
            </li>
        </#if>
    </ul>
</div>
</#if>

七、效果展示

效果展示
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,748評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,165評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,595評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,633評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,435評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,943評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,035評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,175評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,713評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,599評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,788評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,303評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,034評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,412評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,664評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,408評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,747評論 2 370