附上源碼地址源碼地址,點擊"源碼地址"前往github查看
一、創建SpringBoot項目
1)File->New->Project
2)創建Spring Initializr
以及選擇JDK
版本
3)填寫項目信息
4)選擇web
依賴包---Spring Web Starter
或者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
-
選擇
mysql
-
mysql
數據庫信息填寫
-
連接成功后,再次回到
database
,可以看到我們創建的數據庫以及表、字段等信息
三、添加項目依賴庫以及相關配置
1)添加依賴庫
打開pom.xml
文件,依次添加下列依賴庫:
-
添加
FreeMarker
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
-
添加數據庫(
mysql
、jdbc
)
<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
插件,用于生成getter
、setter
方法(需要先在idea設置中添加該插件再進行依賴庫的引入)
a、添加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
文件
-
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
)
-
創建一個名為
HelloWorldController
的java class
-
實現
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層。主要就是去定義與數據庫中的對象相對應的屬性,包括getter
、setter
、toString
方法以及一些構造函數等。
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">×</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
的類:
配置:
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>