Spring Boot和Thymeleaf整合結合JPA實現分頁效果(實例代碼)
在項目里,我需要做一個Spring Boot結合Thymeleaf前端模版,結合JPA實現分頁的演示效果。做的時候發現有些問題,也查了現有網上的不少文檔,發現能全棧實現的不多,所以這里我就把我的做法,全部代碼和步驟貼出來供大家參考。
1 創建項目,用pom.xml引入依賴
這里將創建名為ThymeleafWithDB的Maven,在pom.xml里引入如下的依賴包。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
而在此項目里,對應的Stock庫存表如下所示。
字段名
類型
說明
id
int
主鍵
name
varchar
庫存貨物名
num
int
庫存數量
description
varchar
庫存貨物的描述
2 編寫啟動類這個類是中規中矩的,代碼如下。
package prj;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringBootApp { public static void main(String[] args) { SpringApplication.run(SpringBootApp.class, args); }}
3 在控制器類里,添加支持分頁的方法
@RequestMapping('/listByPage') public ModelAndView listByPage(@RequestParam(value = 'pageNum', defaultValue = '0') int pageNum,@RequestParam(value = 'pageSize', defaultValue = '3') int pageSize) { Page<Stock> stocks=stockService.getStockListByPage(pageNum, pageSize); System.out.println('total page:' + stocks.getTotalPages()); System.out.println('current Page:' + pageNum); ModelAndView modelAndView = new ModelAndView('listByPage'); //傳遞參數 modelAndView.addObject('stocks',stocks); return modelAndView; }
在第2行和第3行定義該方法的參數時,由于表示當前頁的pageNum和每頁數據個數的pageSize參數都是從url請求里以get參數的形式得到,所以在之前要加@RequestParam注解,否則的話就無法從請求里得到這兩個參數。
在該方法的第4行里,調用了stockService對象的getStockListByPage方法,在傳入分頁參數的情況下,得到了當前頁面中的數據。同時為了調試,還在第5行和第6行里,輸出了當前頁和每頁個數的信息。
在拿到當前頁面的數據后,該方法時通過第9行的方法,把它加到modelAndView對象里,并在第10行里,通過該對象,向listByPage視圖返回數據。
4 編寫業務邏輯方法
public Page<Stock> getStockListByPage(int pageNum, int pageSize) { Sort sort = new Sort(Sort.Direction.ASC , 'ID'); Pageable pageable = PageRequest.of(pageNum, pageSize, sort); Page<Stock> stocks = stockRepo.findAll(pageable); return stocks; }
在這個方法的第2行里,首先通過Sort對象,定義了“按ID進行升序排列”的排序方式,隨后通過第3行的PageRequest對象,定義的分頁的方式,這里表示起始數據的pageNum和每頁展示數據的pageSize值,都是來自于外部傳入的參數。
在確定好排序和分頁的方式后,本方法在第4行里,通過調用PagingAndSortingRepository類型對象stockRepo的findAll方法,根據在參數pageable里封裝好的分頁和排序的方式,向MySQL的stock數據表里請求數據,并把得到的數據通過第5行的return語句返回。
5 編寫Repo類
package prj.repo;import org.springframework.data.repository.PagingAndSortingRepository;import org.springframework.stereotype.Component;import prj.model.Stock;@Componentpublic interface StockRepo extends PagingAndSortingRepository<Stock, Integer> { }
從第6行的代碼里大家能看到,該Repo類實現( implements)了JPA里包含分頁和排序功能的PagingAndSortingRepository接口,由于在StockService里調用的findAll方法已經封裝在該JPA接口里了,所以這里在StockRepo類里,甚至不需要再寫代碼。
6 在application.yml文件里編寫JPA和Thymeleaf的配置參數
spring: jpa: show-sql: true hibernate: dll-auto: validate datasource: url: jdbc:mysql://localhost:3306/stock?serverTimezone=GMT username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver thymeleaf: enabled: true content-type: text/html check-template-location: true cache: false prefix: classpath:/templates/ suffix: .html
其中在第1行到第10行的代碼里,給出了JPA和MySQL的相關定義,而在第11行到第17行的代碼里,給出了Thymeleaf模板的參數。
這里用到的配置參數,其實在前文里都已經說明過,不過請注意第2行和第11行的縮進,根據yml配置文件的縮進格式,第11行的thymeleaf其實是和第2行的jpa同級,它們均屬于第1行的spring的子級配置。
7 添加listByPage.html頁面,實現分頁的效果
根據配置,該文件是需要放在resources/templates目錄里,具體代碼如下。
<!DOCTYPE html><html lang='en' xmlns:th='http://www.thymeleaf.org'><head> <meta charset='UTF-8'> <title>庫存列表</title></head><body><table border='2'> <tr> <td>庫存編號</td> <td>庫存貨物</td> <td>數量</td> <td>描述</td> </tr> <tr th:each='stock : ${stocks}'> <td th:text='${stock.ID}'></td> <td th:text='${stock.name}'></td> <td th:text='${stock.num}'></td> <td th:text='${stock.description}'></td> </tr></table><div> <ul> <li> <a th:href='http://www.aoyou183.cn/bcjs/’/listByPage?pageNum=0’' rel='external nofollow' rel='external nofollow' >首頁</a> </li> <li th:if='${stocks.hasPrevious()}'> <a th:href='http://www.aoyou183.cn/bcjs/’/listByPage?pageNum=’ + ${stocks.previousPageable().getPageNumber()}' rel='external nofollow' th:text='上一頁'></a> </li> <li th:if='${stocks.hasNext()}'> <a th:href='http://www.aoyou183.cn/bcjs/’/listByPage?pageNum=’ + ${stocks.nextPageable().getPageNumber()}' rel='external nofollow' th:text='下一頁'></a> </li> <li> <a th:href='http://www.aoyou183.cn/bcjs/’/listByPage?pageNum=’ + ${stocks.getTotalPages() - 1}' rel='external nofollow' rel='external nofollow' >尾頁</a> </li> </ul></div></body></html>
在第22行到第37行的<div>屬性元素里,加入了分頁的效果,具體說明如下。
在第25行的代碼,通過th:href='http://www.aoyou183.cn/bcjs/’/listByPage?pageNum=0’' rel='external nofollow' rel='external nofollow' 代碼,以url參數的形式,向控制器類的listByPage方法,傳遞了pageNum為0的參數,以展示首頁數據。 在顯示“上一頁”的效果前,先需要通過第27行的th:if代碼判斷stocks對象里是否包含了上一頁的數據,如果是,則通過第28行的代碼展示“上一頁”鏈接,請注意這里“上一頁”鏈接所對應的參數,這樣就能通過該鏈接,得到上一頁的數據。 展示“下一頁”的方法和展示“上一頁”的很相似,都是先通過th:if判斷是否有下一頁數據,然后再通過鏈接得到下一頁的數據。 在第34行的代碼里,通過th:href='http://www.aoyou183.cn/bcjs/’/listByPage?pageNum=’ + ${stocks.getTotalPages() - 1}' rel='external nofollow' rel='external nofollow' 的代碼得到了尾頁的數據,請注意這里是用url中pageNum的參數值,得到尾頁的數據。8 觀察效果
編寫完成后,啟動該項目,此時如果在瀏覽器里輸入http://localhost:8080/listByPage,就能看到如下圖所示的效果。
從中大家能看到,上圖里每頁的數據是3條,而且在數據下方展示了對應的分頁鏈接,由于是第一頁,所以沒有包含“上一頁”的鏈接。如果點擊上圖里的“下一頁”鏈接,就能看到頁面跳轉的效果,如下圖所示。
從中大家不僅能看到頁面上的數據變化,而且還能看到在url里,通過攜帶pageNum參數的方式,取到了下一頁數據。并且,由于參數stocks里已經包含了“上一頁”的數據,所以還能看到對應的鏈接。同樣地,大家還能自行點擊“首頁”、“下一頁”和“尾頁”等鏈接,以觀察對應的效果。
到此這篇關于Spring Boot和Thymeleaf整合結合JPA實現分頁效果的文章就介紹到這了,更多相關Spring Boot和Thymeleaf實現分頁內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: