freemarker自定义分页(springboot、bootstrap4)

80183053 2020-03-07

先看下最终效果:

freemarker自定义分页(springboot、bootstrap4)

源码地址:https://github.com/zhouyu629/freemarker-page-demo

实现过程

一、新建springboot项目,导入相关依赖包

<!--web组件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok简化实体类的get set方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- freemarker-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

配置文件,设置freemarker相关参数

spring:
  application:
    name: demo
  freemarker:
    allow-request-override: true
    cache: false
    check-template-location: true
    charset: UTF-8
    content-type: text/html; charset=utf-8
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
    suffix: .ftl
    template-loader-path: classpath:/templates
    settings:
      number_format: 0 # freemarker会自动将整型数字转换为千位分隔,不方便
    http:
      encoding:
        charset: utf-8
        force: true
server:
  port: 8088

二、创建自定义分页类

构造方法里,将页码、分页大小等传进去,自动计算总页数。

package com.demo.util;

import lombok.Data;

import java.util.List;

/**
 * @program: zyproject
 * @description: 分页通用实体类
 * @author: zhouyu(zhouyu629 # qq.com)
 * @create: 2020-02-16
 **/
@Data
public class MyPager<T> {
    private int page; //当前页码,从1开始
    private int pagesize; //分页大小
    private int totalpages; //总页数
    private int totalrecords; //总记录数
    private List<T> list;
    //构造函数中计算总页数
    public MyPager(int page, int pagesize, int totalrecords, List<T> list){
        this.page = page;
        this.pagesize = pagesize;
        this.totalrecords = totalrecords;
        this.list = list;
        //计算总页数
        this.totalpages = totalrecords/pagesize;
        if(totalrecords%pagesize!=0){
            this.totalpages = this.totalpages + 1;
        };
    }
}

顺便再创建一个实体类供测试,直观一点,用hasmap也行。

package com.demo.util;

import lombok.Data;

/**
 * @program: freemarker-page-demo
 * @description: 用户实体
 * @author: zhouyu(zhouyu629 # qq.com)
 * @create: 2020-03-07
 **/
@Data
public class UserEntity {
    private Integer user_id;
    private String user_name;
    private Integer age;
    private String login_name;
    private String mail;
}

三、Controller返回分页数据

实际应用中,pagesize可以写到配置文件或数据库中,允许全局变更。

数据源list也应该从数据层获取。

package com.demo.controller;

import com.demo.util.MyPager;
import com.demo.util.UserEntity;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: freemarker-page-demo
 * @description: demo首页
 * @author: zhouyu(zhouyu629 # qq.com)
 * @create: 2020-03-06
 **/
@Controller
public class IndexController {
    @RequestMapping("/index.html")
    public String index(@RequestParam(name = "page",defaultValue = "1") Integer page,
                     @RequestParam(name = "pagesize",defaultValue = "10") Integer pagesize,
                              Map<String,Object> map){
        //造一些分页数据
        List<UserEntity> list = new ArrayList<>();
        for(int i = ((page-1)*pagesize+1);i<((page-1)*pagesize+pagesize);i++){
            UserEntity userEntity = new UserEntity();
            userEntity.setAge(20);
            userEntity.setLogin_name("user"+i);
            userEntity.setMail("user"+i+"@gmail.com");
            userEntity.setUser_id(i);
            userEntity.setUser_name("user"+i);
            list.add(userEntity);
        }
        MyPager myPager = new MyPager(page,pagesize,500,list);
        map.put("users",myPager);
        return "/index";
    }
}

四、自定义freemarker分页宏

<#--
    参数解释:
    page:当前页码,从1开始
    pagesize:分页大小
    totalpages:总页数。也可以放到模板里计算。这里在MyPager类里已计算过了。
    totalrecords:总记录数
    url:链接地址,自动拼接page参数。为了简单,没有判断当前页面是否有get参数了,直接做了&连接,默认认为原来就有参数。当前你也可以用servlet自己获取当前url及参数,就不用传了。

    以上这些参数除url外均可以从MyPager实例中获取。其实可以直接把mypager实例传进来,为了便于以后扩展,分字段传过来。
-->
<#macro fpage page pagesize totalpages totalrecords url>
    <li class="page-item"><span class="page-link">共条${totalrecords}记录&nbsp;&nbsp;第${page}页/共${totalpages}页</span></li>

    <#--startpage:起始页码就是page,endpage:结束页码,showfirstpage是否显示首页按钮,showlastpage:是否显示末页按钮,showpre是否显示前...,shownext是否显示后...-->
    <#assign startpage = page,endpage=10,showfirstpage=false,showlastpage=false,showpre=false,shownext=false,prepage = 1,nextpage=11>
    <#--是否显示首页按钮及计算初始页码-->
    <#if page gt 1>
        <#assign showfirstpage = true>
        <#--startpage向前挪4页,如果不足4页,则startpage=1-->
        <#assign startpage=(page-4)>
        <#if startpage lte 0>
            <#assign startpage = 1>
        </#if>
    </#if>
    <#--是否显示前n页的...,以及...的链接-->
    <#if page gt 5>
        <#assign showpre = true,prepage=page-5>
    </#if>
    <#--计算endpage-->
    <#if page+pagesize-1 lt totalpages>
        <#assign endpage = page+pagesize-1>
        <#--显示后面的...按钮-->
        <#assign shownext = true>
        <#--后面...的页面码-->
        <#assign nextpage=page+pagesize>
        <#--显示末页-->
        <#assign showlastpage = true>
    <#else>
        <#assign endpage = totalpages>
    </#if>
    <#if endpage lte 0>
        <#assign endpage = 1>
    </#if>

    <#--开始展示-->

    <#--首页-->
    <#if showfirstpage>
        <li class="page-item"><span><a class="page-link" href="${url}&page=1">首页</a></span></li>
    </#if>
    <#--前面的...-->
    <#if showpre>
        <li class="page-item"><span><a class="page-link" href="${url}&page=${prepage}">...</a></span></li>
    </#if>
    <#--显示的页码按钮-->
    <#list startpage..endpage as p>
        <li  class="page-item <#if p == page>active</#if>"><span><a class="page-link" href="${url}&page=${p}">${p}</a></span></li>
    </#list>
    <#--后面的...-->
    <#if shownext>
        <li class="page-item"><span><a class="page-link" href="${url}&page=${nextpage}">...</a></span></li>
    </#if>
    <#--显示尾页-->
    <#if showlastpage>
        <li class="page-item"><span><a class="page-link" href="${url}&page=${totalpages}">末页</a></span></li>
    </#if>
</#macro>

五、html页面引用分页

 核心是这一段,根据后台传过来的MyPager实例users,调用freemarker宏,传递相关参数:

<#import "./public/page.ftl" as fpage />
<@fpage.fpage page=users.page pagesize=users.pagesize totalpages=users.totalpages totalrecords=users.totalrecords url="index.html?key=" />

完整html代码

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-sm">
            <table class="table">
                <thead class="thead-dark">
                <tr>
                    <th scope="col">id</th>
                    <th scope="col">登录名</th>
                    <th scope="col">姓名</th>
                    <th scope="col">mail</th>
                    <th scope="col">年龄</th>
                </tr>
                </thead>
                <tbody>
                <#list users.list as list>
                <tr>
                    <th scope="row">${list.user_id}</th>
                    <td>${list.login_name}</td>
                    <td>${list.user_name}</td>
                    <td>${list.mail}</td>
                    <td>${list.age}</td>
                </tr>
                </#list>
                </tbody>
            </table>
            <!--pager-->
            <nav aria-label="Page navigation example">
                <ul class="pagination">
                    <#import "./public/page.ftl" as fpage />
                    <@fpage.fpage page=users.page pagesize=users.pagesize totalpages=users.totalpages totalrecords=users.totalrecords url="index.html?key=" />
                </ul>
            </nav>
        </div>
    </div> .
</div>

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm//dist/jquery.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm//dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm//dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

打完收功!

相关推荐

89314493 / 0评论 2020-06-03