Through paging techniques, we can only show some of the products.

Add More Products into Database

Run the following SQL inside the database:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
USE shop;

INSERT INTO
product(`created_at`, `updated_at`, `sku`, `name`, `stock`, `price`, `description`)
VALUES
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-003", "Yellow T-Shirt", 99, 999, "Yellow T-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-004", "Pink T-Shirt", 99, 999, "Pink T-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-005", "Grey T-Shirt", 99, 999, "GreyT-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-006", "Blue T-Shirt", 99, 999, "Blue T-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-007", "Black T-Shirt", 99, 999, "Black T-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-008", "White T-Shirt", 99, 999, "White T-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-009", "Purple T-Shirt", 99, 999, "Purple T-Shirt For Sale!"),
(UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), "SKU-0010", "Light T-Shirt", 99, 999, "Light T-Shirt For Sale!");

Create Pagination Utilities

Create PageHelper

  • Right click common/src/main/java/co.dongchen.shop.common/util directory: New > Java Class
  • Fill in “PageHelper”
  • Click “OK” button
img

Copy and paste the following content into PageHelper.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package co.dongchen.shop.common.util;

public class PageHelper {

    private static final Integer PAGE_SIZE = 5;

    private Integer pageSize;
    private Integer pageNumber;
    private Integer offSet;
    private Integer limit;

    public PageHelper() {
        this(PAGE_SIZE, 1);
    }

    public PageHelper(Integer pageSize, Integer pageNumber) {
        this.pageSize = pageSize;
        this.pageNumber = pageNumber;
        this.offSet = pageSize * (pageNumber - 1);
        this.limit = pageSize;
    }

    public static PageHelper init(Integer pageSize, Integer pageNumber) {
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        if (pageNumber == null) {
            pageNumber = 1;
        }
        return new PageHelper(pageSize, pageNumber);
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(Integer pageNumber) {
        this.pageNumber = pageNumber;
    }

    public Integer getOffSet() {
        return offSet;
    }

    public void setOffSet(Integer offSet) {
        this.offSet = offSet;
    }

    public Integer getLimit() {
        return limit;
    }

    public void setLimit(Integer limit) {
        this.limit = limit;
    }
}

Create Pagination

  • Right click common/src/main/java directory: New > Package
  • Fill in “co.dongchen.shop.common.util.pager”
  • Click “OK” button
img
  • Right click common/src/main/java/co.dongchen.shop.common/util/pager directory: New > Java Class
  • Fill in “Pagination”
  • Click “OK” button
img

Copy and paste the following content into Pagination.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package co.dongchen.shop.common.util.pager;

import com.google.common.collect.Lists;

import java.util.List;

public class Pagination {

    private Integer pageSize;
    private Integer pageNumber;
    private Long count;
    private List<Integer> pageNumbers = Lists.newArrayList();

    public Pagination(Integer pageSize, Integer pageNumber, Long count) {
        this.pageSize = pageSize;
        this.pageNumber = pageNumber;
        this.count = count;
        for (int i = 1; i <= pageNumber; i++) {
            pageNumbers.add(i);
        }
        Long pageCount = count / pageSize + ((count % pageSize == 0) ? 0 : 1);
        if (pageCount > pageNumber) {
            for (int i = pageNumber + 1; i <= pageCount; i++) {
                pageNumbers.add(i);
            }
        }
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(Integer pageNumber) {
        this.pageNumber = pageNumber;
    }

    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }

    public List<Integer> getPageNumbers() {
        return pageNumbers;
    }

    public void setPageNumbers(List<Integer> pageNumbers) {
        this.pageNumbers = pageNumbers;
    }
}

Create PagingData

  • Right click common/src/main/java/co.dongchen.shop.common/util/pager directory: New > Java Class
  • Fill in “PagingData”
  • Click “OK” button
img

Copy and paste the following content into PagingData.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package co.dongchen.shop.common.util.pager;

import java.util.List;

public class PagingData<T> {

    private List<T> list;
    private Pagination pagination;

    public PagingData(Pagination pagination, List<T> list) {
        this.pagination = pagination;
        this.list = list;
    }

    public static <T> PagingData<T> initPaging(List<T> list, long count, int pageSize, int pageNumber) {
        Pagination pagination = new Pagination(pageSize, pageNumber, count);
        return new PagingData(pagination, list);
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public Pagination getPagination() {
        return pagination;
    }

    public void setPagination(Pagination pagination) {
        this.pagination = pagination;
    }
}

Update Product Mapper

Update ProductMapper interface

Copy and paste the following content into ProductMapper.java under the service/src/main/java/co.dongchen.shop/mapper directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package co.dongchen.shop.mapper;

import co.dongchen.shop.common.model.Product;
import co.dongchen.shop.common.util.PageHelper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface ProductMapper {

    List<Product> queryPagedProducts(@Param("productCondition") Product productCondition, @Param("pageHelperCondition") PageHelper pageHelperCondition);

    Long queryPagedCount(@Param("productCondition") Product productCondition);

    int insert(Product product);
}

Update product.xml

Copy and paste the following content into product.xml under the service/src/resources/mapper directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="co.dongchen.shop.mapper.ProductMapper">
    <sql id="productFields">
        p.id, p.created_at, p.updated_at, p.sku, p.name, p.stock, p.price, p.is_enabled, p.images, p.description
    </sql>
    <sql id="whereCondition">
        <where>
            <if test="productCondition.id != null and productCondition.id != 0">
                and p.id = #{productCondition.id}
            </if>
            <if test="productCondition.isEnabled">
                and p.is_enabled = #{productCondition.isEnabled}
            </if>
            <if test="productCondition.name != null and productCondition.name != ''">
                <bind name="likeName" value="'%' + productCondition.name + '%'"/>
                and p.name like #{likeName}
            </if>
        </where>
    </sql>
    <select id="queryPagedProducts" resultType="product">
        select <include refid="productFields"/>
        from product p
        <include refid="whereCondition"/>
        <if test="pageHelperCondition.offSet != null and pageHelperCondition.limit != null">
            limit #{pageHelperCondition.offSet},#{pageHelperCondition.limit}
        </if>
        <if test="pageHelperCondition.offSet == null and pageHelperCondition.limit != null">
            limit #{pageHelperCondition.limit}
        </if>
    </select>
    <select id="queryPagedCount" resultType="long">
        select count(id)
        from product p
        <include refid="whereCondition"/>
    </select>
</mapper>

Update ProductService class

Copy and paste the following content into ProductService.java under the service/src/java/co.dongchen.shop/service directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package co.dongchen.shop.service;

import co.dongchen.shop.common.model.Product;
import co.dongchen.shop.common.util.PageHelper;
import co.dongchen.shop.common.util.pager.PagingData;
import co.dongchen.shop.mapper.ProductMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductService {

    @Value("${fileserver.img_path}")
    private String imgPath;

    @Autowired
    private ProductMapper productMapper;

    public PagingData<Product> getProducts(Product productCondition, PageHelper pageHelper) {
        List<Product> products = Lists.newArrayList();
        products = queryWithImgs(productCondition, pageHelper);
        Long count = productMapper.queryPagedCount(productCondition);
        return PagingData.initPaging(products, count, pageHelper.getPageSize(), pageHelper.getPageNumber());
    }

    private List<Product> queryWithImgs(Product productCondition, PageHelper pageHelper) {
        List<Product> products = productMapper.queryPagedProducts(productCondition, pageHelper);
        products.forEach(p -> {
            p.setMainImage(imgPath + p.getMainImage());
            p.setImageList(p.getImageList().stream().map(img -> imgPath + img).collect(Collectors.toList()));
        });
        return products;
    }
}

Update ProductController class

Copy and paste the following content into ProductController.java under the controller/src/java/co.dongchen.shop/controller directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package co.dongchen.shop.controller;

import co.dongchen.shop.common.model.Product;
import co.dongchen.shop.common.util.PageHelper;
import co.dongchen.shop.common.util.pager.PagingData;
import co.dongchen.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("/product/pagination")
    public String pagination(PageHelper pageHelper, Product productCondition, ModelMap modelMap) {
        PagingData<Product> pageData = productService.getProducts(productCondition, PageHelper.init(pageHelper.getPageSize(), pageHelper.getPageNumber()));
        modelMap.put("pageData", pageData);
        modelMap.put("productCondition", productCondition);
        return "/product/pagination";
    }
}

Update common.ftl in Controller Module

Append the following content into common.ftl template:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<#macro js>
    <script type="text/javascript" src="/static/common/js/common.js"></script>
</#macro>

<#macro paging pagination>
<ul class="pagination">
    <#list pagination.pageNumbers as page>
        <#if pagination.pageNumber==page>
        <li class="active"><a href="#">${page}</a></li>
        <#else>
        <li><a href="javascript:void(0)"  onclick="nextPage(${page},${pagination.pageSize})">${page}</a></li>
    </#if>
    </#list>
</ul><!-- /.pagination-->
</#macro>

Create common.js in Controller Module

  • Right click controller/src/main/resources directory: New > Directory
  • Fill in “static/static/common/js”
  • Click “OK” button
img
  • Right click static.static.common.js directory: New > File
  • Fill in “common.js”
  • Click “OK” button
img

Copy and paste the following content into common.js:

1
2
3
4
5
6
function nextPage(pageNum, pageSize) {
    var url = window.location.href;
    url = url.split('?')[0].split('#')[0];
    var data = "?pageNumber=" + pageNum + "&pageSize=" + pageSize;
    window.location.href = url + data;
}

Create pagination.ftl in Controller Module

  • Right click controller/src/main/resources/templates directory: New > Directory
  • Fill in “product”
  • Click “OK” button
img
  • Right click product directory: New > File
  • Fill in “pagination.ftl”
  • Click “OK” button
img

Copy and paste the following content into pagination.ftl:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<div>
    <#foreach product in pageData.list>
        <div>
            <p>${product.name}</p>
        </div>
    </#foreach>
</div>
<div>
    <@common.paging pageData.pagination/>
</div>
<@common.js/>

Remove a Method from FreeMarkerController

Remove the following method from FreeMarkerController:

1
2
3
4
5
6
7
    @RequestMapping("hellofreemarker")
    public String helloFreeMarker(ModelMap modelMap) {
        List<Product> products = productService.getProducts();
        Product firstProduct = products.get(0);
        modelMap.put("product", firstProduct);
        return "hello-freemarker";
    }

See here for more information about how to insert data into database.

Verify

Run the App

1
2
// Short Cut for "Run the Program"
Alt + Shift + F10
img

Choose the correspondent option and press enter.

View Product List Page in the Browser

1
http://localhost:8080/product/pagination
img

Click linkage number 2 to the second page:

img

Buy me a coffeeBuy me a coffee