PagingAndSortingRepository –如何与Thymeleaf一起使用
在本教程中,我將演示如何通過分頁顯示Thymeleaf中的企業客戶列表。
1 –項目結構
我們有一個正常的Maven項目結構。
2 –項目依賴性
除了正常的Spring依賴關系之外,我們還添加Thymeleaf和hsqldb,因為我們使用的是嵌入式數據庫。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.michaelcgood</groupId><artifactId>michaelcgood-pagingandsorting</artifactId><version>0.0.1</version><packaging>jar</packaging><name>PagingAndSortingRepositoryExample</name><description>Michael C Good - PagingAndSortingRepository</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.6.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.hsqldb</groupId><artifactId>hsqldb</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>3 –型號
我們為客戶定義以下字段:
- 唯一標識符
- 客戶名稱
- 客戶地址
- 當前發票上的欠款
getter和setter在Spring Tool Suite中快速生成。
要將此模型注冊到@SpringBootApplication,需要@Entity批注。
ClientModel.java
package com.michaelcgood.model;import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;@Entity public class ClientModel {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public Integer getCurrentInvoice() {return currentInvoice;}public void setCurrentInvoice(Integer currentInvoice) {this.currentInvoice = currentInvoice;}private String name;private String address;private Integer currentInvoice;}與ClientModel不同,PagerModel只是一個POJO(普通的舊Java對象)。 沒有導入,因此沒有注釋。 此PagerModel僅用于幫助我們網頁上的分頁。 閱讀Thymeleaf模板并查看演示圖片后,請重新訪問此模型。 當您在上下文中考慮它時,PagerModel更有意義。
PagerModel.java
package com.michaelcgood.model;public class PagerModel {private int buttonsToShow = 5;private int startPage;private int endPage;public PagerModel(int totalPages, int currentPage, int buttonsToShow) {setButtonsToShow(buttonsToShow);int halfPagesToShow = getButtonsToShow() / 2;if (totalPages <= getButtonsToShow()) {setStartPage(1);setEndPage(totalPages);} else if (currentPage - halfPagesToShow <= 0) {setStartPage(1);setEndPage(getButtonsToShow());} else if (currentPage + halfPagesToShow == totalPages) {setStartPage(currentPage - halfPagesToShow);setEndPage(totalPages);} else if (currentPage + halfPagesToShow > totalPages) {setStartPage(totalPages - getButtonsToShow() + 1);setEndPage(totalPages);} else {setStartPage(currentPage - halfPagesToShow);setEndPage(currentPage + halfPagesToShow);}}public int getButtonsToShow() {return buttonsToShow;}public void setButtonsToShow(int buttonsToShow) {if (buttonsToShow % 2 != 0) {this.buttonsToShow = buttonsToShow;} else {throw new IllegalArgumentException("Must be an odd value!");}}public int getStartPage() {return startPage;}public void setStartPage(int startPage) {this.startPage = startPage;}public int getEndPage() {return endPage;}public void setEndPage(int endPage) {this.endPage = endPage;}@Overridepublic String toString() {return "Pager [startPage=" + startPage + ", endPage=" + endPage + "]";}}4 –儲存庫
PagingAndSortingRepository是CrudRepository的擴展。 唯一的區別是,它允許您對實體進行分頁。 注意,我們用@Repository注釋了接口,以使其對@SpringBootApplication可見。
ClientRepository.java
package com.michaelcgood.dao;import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository;import com.michaelcgood.model.ClientModel;@Repository public interface ClientRepository extends PagingAndSortingRepository<ClientModel,Long> {}5 –控制器
我們在課程開始時定義一些變量。 我們只想一次顯示3個頁面按鈕。 初始頁面是結果的第一頁,頁面上的初始項目數是5,并且用戶能夠每頁獲得5或10個結果。
我們使用addtorepository()方法將一些示例值添加到我們的存儲庫中,該方法將在此類中進一步定義。 使用addtorepository method(),我們將幾個“客戶端”添加到我們的存儲庫中,其中許多都是帽子公司,因為我沒有想法。
這里使用ModelAndView而不是Model。 而是使用ModelAndView,因為它既是ModelMap也是視圖對象的容器。 它允許控制器將兩個值作為單個值返回。 這是我們正在做的事情所希望的。
ClientController.java
package com.michaelcgood.controller;import java.util.Optional;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.michaelcgood.model.PagerModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest;import com.michaelcgood.dao.ClientRepository; import com.michaelcgood.model.ClientModel;@Controller public class ClientController {private static final int BUTTONS_TO_SHOW = 3;private static final int INITIAL_PAGE = 0;private static final int INITIAL_PAGE_SIZE = 5;private static final int[] PAGE_SIZES = { 5, 10};@AutowiredClientRepository clientrepository;@GetMapping("/")public ModelAndView homepage(@RequestParam("pageSize") Optional<Integer> pageSize,@RequestParam("page") Optional<Integer> page){if(clientrepository.count()!=0){;//pass}else{addtorepository();}ModelAndView modelAndView = new ModelAndView("index");//// Evaluate page size. If requested parameter is null, return initial// page sizeint evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);// Evaluate page. If requested parameter is null or less than 0 (to// prevent exception), return initial size. Otherwise, return value of// param. decreased by 1.int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;// print repoSystem.out.println("here is client repo " + clientrepository.findAll());Page<ClientModel> clientlist = clientrepository.findAll(new PageRequest(evalPage, evalPageSize));System.out.println("client list get total pages" + clientlist.getTotalPages() + "client list get number " + clientlist.getNumber());PagerModel pager = new PagerModel(clientlist.getTotalPages(),clientlist.getNumber(),BUTTONS_TO_SHOW);// add clientmodelmodelAndView.addObject("clientlist",clientlist);// evaluate page sizemodelAndView.addObject("selectedPageSize", evalPageSize);// add page sizesmodelAndView.addObject("pageSizes", PAGE_SIZES);// add pagermodelAndView.addObject("pager", pager);return modelAndView;}public void addtorepository(){//below we are adding clients to our repository for the sake of this exampleClientModel widget = new ClientModel();widget.setAddress("123 Fake Street");widget.setCurrentInvoice(10000);widget.setName("Widget Inc");clientrepository.save(widget);//next clientClientModel foo = new ClientModel();foo.setAddress("456 Attorney Drive");foo.setCurrentInvoice(20000);foo.setName("Foo LLP");clientrepository.save(foo);//next clientClientModel bar = new ClientModel();bar.setAddress("111 Bar Street");bar.setCurrentInvoice(30000);bar.setName("Bar and Food");clientrepository.save(bar);//next clientClientModel dog = new ClientModel();dog.setAddress("222 Dog Drive");dog.setCurrentInvoice(40000);dog.setName("Dog Food and Accessories");clientrepository.save(dog);//next clientClientModel cat = new ClientModel();cat.setAddress("333 Cat Court");cat.setCurrentInvoice(50000);cat.setName("Cat Food");clientrepository.save(cat);//next clientClientModel hat = new ClientModel();hat.setAddress("444 Hat Drive");hat.setCurrentInvoice(60000);hat.setName("The Hat Shop");clientrepository.save(hat);//next clientClientModel hatB = new ClientModel();hatB.setAddress("445 Hat Drive");hatB.setCurrentInvoice(60000);hatB.setName("The Hat Shop B");clientrepository.save(hatB);//next clientClientModel hatC = new ClientModel();hatC.setAddress("446 Hat Drive");hatC.setCurrentInvoice(60000);hatC.setName("The Hat Shop C");clientrepository.save(hatC);//next clientClientModel hatD = new ClientModel();hatD.setAddress("446 Hat Drive");hatD.setCurrentInvoice(60000);hatD.setName("The Hat Shop D");clientrepository.save(hatD);//next clientClientModel hatE = new ClientModel();hatE.setAddress("447 Hat Drive");hatE.setCurrentInvoice(60000);hatE.setName("The Hat Shop E");clientrepository.save(hatE);//next clientClientModel hatF = new ClientModel();hatF.setAddress("448 Hat Drive");hatF.setCurrentInvoice(60000);hatF.setName("The Hat Shop F");clientrepository.save(hatF);}}6 – Thymeleaf模板
在Thymeleaf模板中,需要注意的兩個最重要的事情是:
- 胸腺標準方言
- Java腳本
就像在CrudRepository中一樣,我們使用th:each =” clientlist:$ {clientlist}”遍歷PagingAndSortingRepository。 除了不是存儲庫中的每個項目都是Iterable之外,該項目都是頁面。
使用select class =“ form-control pagination” id =“ pageSizeSelect”,我們允許用戶選擇5或10的頁面大小。我們在Controller中定義了這些值。
接下來是允許用戶瀏覽各個頁面的代碼。 這是我們的PagerModel進入使用的地方。
changePageAndSize()函數是JavaScript函數,它將在用戶更改頁面大小時更新頁面大小。
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"><head> <!-- CSS INCLUDE --> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"crossorigin="anonymous"></link><!-- EOF CSS INCLUDE --> <style> .pagination-centered {text-align: center; }.disabled {pointer-events: none;opacity: 0.5; }.pointer-disabled {pointer-events: none; } </style></head> <body><!-- START PAGE CONTAINER --><div class="container-fluid"><!-- START PAGE SIDEBAR --><!-- commented out <div th:replace="fragments/header :: header">?</div> --><!-- END PAGE SIDEBAR --><!-- PAGE TITLE --><div class="page-title"><h2><span class="fa fa-arrow-circle-o-left"></span> Client Viewer</h2></div><!-- END PAGE TITLE --><div class="row"><table class="table datatable"><thead><tr><th>Name</th><th>Address</th><th>Load</th></tr></thead><tbody><tr th:each="clientlist : ${clientlist}"><td th:text="${clientlist.name}">Text ...</td><td th:text="${clientlist.address}">Text ...</td><td><button type="button"class="btn btn-primary btn-condensed"><i class="glyphicon glyphicon-folder-open"></i></button></td></tr></tbody></table><div class="row"><div class="form-group col-md-1"><select class="form-control pagination" id="pageSizeSelect"><option th:each="pageSize : ${pageSizes}" th:text="${pageSize}"th:value="${pageSize}"th:selected="${pageSize} == ${selectedPageSize}"></option></select></div><div th:if="${clientlist.totalPages != 1}"class="form-group col-md-11 pagination-centered"><ul class="pagination"><li th:class="${clientlist.number == 0} ? disabled"><aclass="pageLink"th:href="@{/(pageSize=${selectedPageSize}, page=1)}">?</a></li><li th:class="${clientlist.number == 0} ? disabled"><aclass="pageLink"th:href="@{/(pageSize=${selectedPageSize}, page=${clientlist.number})}">←</a></li><lith:class="${clientlist.number == (page - 1)} ? 'active pointer-disabled'"th:each="page : ${#numbers.sequence(pager.startPage, pager.endPage)}"><a class="pageLink"th:href="@{/(pageSize=${selectedPageSize}, page=${page})}"th:text="${page}"></a></li><lith:class="${clientlist.number + 1 == clientlist.totalPages} ? disabled"><a class="pageLink"th:href="@{/(pageSize=${selectedPageSize}, page=${clientlist.number + 2})}">→</a></li><lith:class="${clientlist.number + 1 == clientlist.totalPages} ? disabled"><a class="pageLink"th:href="@{/(pageSize=${selectedPageSize}, page=${clientlist.totalPages})}">?</a></li></ul></div></div></div><!-- END PAGE CONTENT --><!-- END PAGE CONTAINER --></div><scriptsrc="https://code.jquery.com/jquery-1.11.1.min.js"integrity="sha256-VAvG3sHdS5LqTT+5A/aeq/bZGa/Uj04xKxY8KM/w9EE="crossorigin="anonymous"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"crossorigin="anonymous"></script><script th:inline="javascript">/*<![CDATA[*/$(document).ready(function() {changePageAndSize(); });function changePageAndSize() {$('#pageSizeSelect').change(function(evt) {window.location.replace("/?pageSize=" + this.value + "&page=1");}); }/*]]>*/</script></body> </html>7 –配置
可以根據您的喜好更改以下屬性,但這正是我所希望的環境。
application.properties
#================================== # = Thymeleaf configurations #================================== spring.thymeleaf.check-template-location=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.content-type=text/html spring.thymeleaf.cache=false server.contextPath=/8 –演示
這是主頁。
這是第二頁。
我可以將頁面上的項目數量更改為10。
源代碼在 Github上
翻譯自: https://www.javacodegeeks.com/2017/10/pagingandsortingrepository-use-thymeleaf.html
總結
以上是生活随笔為你收集整理的PagingAndSortingRepository –如何与Thymeleaf一起使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 67数字代表什么含义 67数字的寓意
- 下一篇: 双标男是啥意思 双标男属于什么意思呢