Spring Boot and Thymeleaf integration, combined with JPA to achieve paging effect

    In the project, I need to make a Spring Boot combined with Thymeleaf front-end template, combined with JPA to achieve the demonstration effect of paging. When I did it, I found some problems. I also checked a lot of existing documents on the Internet, and found that there are not many full-stack implementations. So here I will post my approach, all the code and steps for your reference.

1 Create a project and use pom.xml to introduce dependencies

    Here, a Maven named ThymeleafWithDB will be created, and the following dependency packages will be introduced in pom.xml.

1	    <dependencies>
2	        <dependency>
3	            <groupId>org.springframework.boot</groupId>
4	            <artifactId>spring-boot-starter-web</artifactId>
5	        </dependency>
6	        <dependency>
7	            <groupId>org.springframework.boot</groupId>            
8	<artifactId>spring-boot-starter-thymeleaf</artifactId>
9	        </dependency>
10	    </dependencies>

    In this project, the corresponding Stock inventory table is shown below.

Field name

Types of

Description

id

int

Primary key

name

varchar

Inventory goods name

on one

int

Inventory quantity

description

varchar

Description of inventory goods

2 write startup class

   This class is quite satisfactory, the code is as follows.

1	package prj;
2	import org.springframework.boot.SpringApplication;
3	import org.springframework.boot.autoconfigure.SpringBootApplication;
4	@SpringBootApplication
5	public class SpringBootApp {
6	    public static void main(String[] args) {
7	        SpringApplication.run(SpringBootApp.class, args);
8	    }
9	}

3 In the controller class, add a method to support paging

1	    @RequestMapping("/listByPage")
2	    public ModelAndView listByPage(@RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
3	@RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
4	        Page<Stock> stocks=stockService.getStockListByPage(pageNum, pageSize);
5	        System.out.println("total page:" + stocks.getTotalPages());
6	        System.out.println("current Page:" + pageNum);
7	        ModelAndView modelAndView = new ModelAndView("listByPage");
8	        //传递参数
9	        modelAndView.addObject("stocks",stocks);
10	        return modelAndView;
11	    }

    When defining the parameters of the method in lines 2 and 3, since the pageSize parameter representing the pageNum of the current page and the number of data per page is obtained from the url request in the form of a get parameter, it is necessary to add @RequestParam before Note, otherwise you will not be able to get these two parameters from the request.

    In the fourth line of the method, the getStockListByPage method of the stockService object is called, and the data in the current page is obtained when the paging parameters are passed in. At the same time, for debugging, the information of the current page and the number of each page is also output in the 5th and 6th lines.

    After getting the data of the current page, this method uses the method in line 9 to add it to the modelAndView object, and in line 10, the data is returned to the listByPage view through this object.

4 Writing business logic methods

1	public Page<Stock> getStockListByPage(int pageNum, int pageSize) {
2	        Sort sort = new Sort(Sort.Direction.ASC , "ID");
3	        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
4	        Page<Stock> stocks = stockRepo.findAll(pageable);
5	        return stocks;
6	    }

    In the second line of this method, the Sort object is used to define the sorting method of "ascending order by ID", and then the PageRequest object in the third line is used to define the paging method, where the pageNum and the pageNum of the starting data are defined. The pageSize value of the data displayed on each page comes from external parameters.

    After determining the sorting and paging method, in line 4, this method calls the findAll method of the PagingAndSortingRepository type object stockRepo to request the MySQL stock data table according to the paging and sorting method encapsulated in the parameter pageable Data, and return the obtained data through the return statement on line 5.

5 Write Repo class

1	package prj.repo;
2	import org.springframework.data.repository.PagingAndSortingRepository;
3	import org.springframework.stereotype.Component;
4	import prj.model.Stock;
5	@Component
6	public interface StockRepo extends PagingAndSortingRepository<Stock, Integer> {  }

    As you can see from the code in line 6, the Repo class implements the PagingAndSortingRepository interface that contains paging and sorting functions in JPA. Since the findAll method called in StockService has been encapsulated in the JPA interface, so here In the StockRepo class, you don't even need to write code.

6 Write the configuration parameters of JPA and Thymeleaf in the application.yml file    

1	spring:
2	  jpa:
3	    show-sql: true
4	    hibernate:
5	      dll-auto: validate
6	  datasource:
7	    url: jdbc:mysql://localhost:3306/stock?serverTimezone=GMT
8	    username: root
9	    password: 123456
10	    driver-class-name: com.mysql.jdbc.Driver
11	  thymeleaf:
12	    enabled: true
13	    content-type: text/html
14	    check-template-location: true
15	    cache: false
16	    prefix: classpath:/templates/
17	    suffix: .html

    Among them, in the code from lines 1 to 10, the relevant definitions of JPA and MySQL are given, and in the code from lines 11 to 17, the parameters of the Thymeleaf template are given.

    The configuration parameters used here have actually been explained in the previous article, but please pay attention to the indentation of the 2nd and 11th lines. According to the indentation format of the yml configuration file, the thymeleaf on the 11th line is actually the same as the 2nd line. The jpa is at the same level, and they all belong to the child configuration of spring in line 1.

7 Add the listByPage.html page to achieve the effect of paging

    According to the configuration, the file needs to be placed in the resources/templates directory. The specific code is as follows.

1	<!DOCTYPE html>
2	<html  lang="en" xmlns:th="http://www.thymeleaf.org">
3	<head>
4	    <meta charset="UTF-8">
5	    <title>库存列表</title>
6	</head>
7	<body>
8	<table border="2">
9	    <tr>
10	        <td>库存编号</td>
11	        <td>库存货物</td>
12	        <td>数量</td>
13	        <td>描述</td>
14	    </tr>
15	    <tr th:each="stock : ${stocks}">
16	        <td th:text="${stock.ID}"></td>
17	        <td th:text="${stock.name}"></td>
18	        <td th:text="${stock.num}"></td>
19	        <td th:text="${stock.description}"></td>
20	    </tr>
21	</table>
22	<div>
23	    <ul>
24	        <li>
25	            <a th:href="'/listByPage?pageNum=0'">首页</a>
26	        </li>
27	        <li th:if="${stocks.hasPrevious()}">
28	            <a th:href="'/listByPage?pageNum=' + ${stocks.previousPageable().getPageNumber()}" th:text="上一页"></a>
29	        </li>
30	        <li th:if="${stocks.hasNext()}">
31	            <a th:href="'/listByPage?pageNum=' + ${stocks.nextPageable().getPageNumber()}" th:text="下一页"></a>
32	        </li>
33	        <li>
34	            <a th:href="'/listByPage?pageNum=' + ${stocks.getTotalPages() - 1}">尾页</a>
35	        </li>
36	    </ul>
37	</div>
38	</body>
39	</html>

    In the <div> attribute element from line 22 to line 37, the effect of paging is added. The specific instructions are as follows.

  1. In the code on line 25, pass th:href="'/listByPage?pageNum=0'" code, in the form of url parameter, to the listByPage method of the controller class, passing a parameter with pageNum of 0 to display the home page data .
  2. Before displaying the effect of "previous page", it is necessary to determine whether the stocks object contains the data of the previous page through the th:if code on line 27. If so, display "previous page" through the code on line 28 "Link, please pay attention to the parameters corresponding to the "previous page" link here, so that you can get the data of the previous page through this link.
  3. The method of displaying the "next page" is very similar to that of displaying the "previous page". Firstly, th:if is used to determine whether there is data on the next page, and then the data on the next page is obtained through the link.
  4. In the code on line 34, the data of the last page is obtained through the code th:href="'/listByPage?pageNum=' + ${stocks.getTotalPages()-1}". Please note that the pageNum in the url is used here The parameter value of, get the data of the last page.

8 Observation effect

    After writing, start the project. At this time, if you enter http://localhost:8080/listByPage in the browser, you can see the effect as shown in the figure below.

    As you can see, there are 3 pieces of data on each page in the above figure, and the corresponding paging link is displayed below the data. Since it is the first page, there is no link to "previous page". If you click on the "Next Page" link in the picture above, you can see the effect of the page jump, as shown in the picture below.

    From this, you can not only see the data changes on the page, but also see that in the URL, the next page of data is retrieved by carrying the pageNum parameter. And, because the parameter stocks already contains the "previous page" data, you can still see the corresponding link. Similarly, you can also click on the "Home", "Next" and "Last Page" links to observe the corresponding effects.

Guess you like

Origin blog.csdn.net/sxeric/article/details/114117184