程序员必看内容连续集之 SpringBoot04 Springboot视图渲染

发布于:2022-11-07 ⋅ 阅读:(8) ⋅ 点赞:(0) ⋅ 评论:(0)

目录

一、Freemarker简介及入门

二、Freemarker语法

三、Freemarker综合案例


一、Freemarker简介及入门

参考网址:

http://freemarker.foofun.cn/ 

使用Freemarker的步骤:

 首先我们来创建一个Springboot项目基于mybatis并且拥有freemarker配置:

刚刚开始我们右键创建类是没有Freemarker选项的,所以我们进行配置File>Settings>Editor>File and Code Templates

①首先复制HTML模板

 ②修改负责的HTML模板

 ③配置application.properties

mybatis:
    mapper-locations: classpath:mappers/**/*xml
    type-aliases-package: com.zq.springboot04.mybatis.entity
server:
    port: 8080
spring:
    application:
        name: springbootviem
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
        username: root
    freemarker:
        cache: false
        charset: utf-8
        expose-request-attributes: true
        expose-session-attributes: true
        suffix: .ftl
        template-loader-path: classpath:/templates/
#    resources:
#        static-locations: classpath:/static/# 应用服务 WEB 访问端口
    mvc:
        static-path-pattern: classpath:/static/

降低MySQL的版本

测试:

 index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
欢迎来到freemarker首页
</body>
</html>

ViemController:

package com.zq.springboot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(){
        System.out.println("come in ...");
//         suffix: .ftl
//        template-loader-path: classpath:/templates/
//        /templates/index.ftl
        return "index";
    //这里的return的字符串和页面名称对应
    }
}

启动项目测试(在application.properties文件中运行main方法):启动成功!

二、Freemarker语法

接下来我们开始介绍Freemarker的语法

1、取值的用法:

1.1获取后台数据方法:

我们从后台传递一个name到前台邦值怎么做:

index.ftl(前台页面):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>取值</h3>
    <p>1.1 后台与前台传递数据</p>
    <#-- 如果name的值为空,而且没有提供默认值,那么就会报错 -->
    ${name}
</body>
</html>

ViemController(后台):

package com.zq.springboot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("name","zq");
        return "index";
    }
}

 1.2对与后台传递数据为空解决不报错方法:

①添加 ! 号

index.ftl(前台如果没有拿到数据就会报错name用!即可解决):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>取值</h3>
    <p>1.1 提供默认值</p>
    <#-- 如果name的值为空,而且没有提供默认值,那么就会报错 -->
    <#--${name}-->

    <#-- 解决接收值为空报错 -->
    ${name !}
</body>
</html>

ViemController(后台):

package com.zq.springboot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(Model model){

        return "index";
    }
}

②设置默认值(当后台没有值,取默认值,有则反之)

index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>取值</h3>
    <p>1.1 提供默认值</p>
    <#-- 如果name的值为空,而且没有提供默认值,那么就会报错 -->
    <#--${name}-->

    <#-- 解决接收值为空报错 -->
    ${name !'我是默认值'}
</body>
</html>

ViemController(后台):

package com.zq.springboot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(Model model){

        return "index";
    }
}

 1.3对null值进行判断处理

①exist用于逻辑判断

 index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>取值</h3>
    <p>1.1 提供默认值</p>
    <#-- 如果name的值为空,而且没有提供默认值,那么就会报错 -->
    <#--${name}-->

    <#-- 解决接收值为空报错 -->
    <#--${name !'我是默认值'}-->
    <br>

    <p>1.2 对null值先进行判断</p>
    ①exist用在逻辑判断
    <#if name?exists>
    ${name}
    </#if>
    <br>

</body>
</html>

②??是判断对象是否为空

 index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>取值</h3>
    <p>1.1 提供默认值</p>
    <#-- 如果name的值为空,而且没有提供默认值,那么就会报错 -->
    <#--${name}-->

    <#-- 解决接收值为空报错 -->
    <#--${name !'我是默认值'}-->
    <br>

    <p>1.2 对null值先进行判断</p>
    ①exist用在逻辑判断
    <#if name?exists>
    ${name}
    </#if>
    <br>

    ②??是判断对象是否为空
    <#if name??>
    ${name}
    </#if>
    <br>

</body>
</html>

③if_exists用来打印东西

index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>取值</h3>
    <p>1.1 提供默认值</p>
    <#-- 如果name的值为空,而且没有提供默认值,那么就会报错 -->
    <#--${name}-->

    <#-- 解决接收值为空报错 -->
    <#--${name !'我是默认值'}-->
    <br>

    <p>1.2 对null值先进行判断</p>
    ①exist用在逻辑判断
    <#if name?exists>
    ${name}
    </#if>
    <br>

    ②??是判断对象是否为空
    <#if name??>
    ${name}
    </#if>
    <br>

    ③if_exists用来打印东西
    ${name?if_exists}
    <br>
</body>
</html>

当后台有数据传递时:(当后台传递了数据就会绑定对应的数据)

 当后台没有数据传递时:(当后台没有传递数据就会不会渲染对应的数据值)

2、条件的用法:

index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>条件</h3>
<#if sex='nv'>
    女
<#elseif sex='nan'>
    男
<#else>
    未知
</#if>
</body>
</html>

ViemController:

package com.zq.springboot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("sex","nan");
        return "index";
    }
}

测试:

3、循环的用法:

3.1取出数组中的元素

index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title></title>
</head>
<body>
<h3>循环</h3>
1)取出数组中的元素
<#list arr as a>
     #{a}<br>
</#list>
</body>
</html>

ViemController:

package com.zq.springboot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("arr",new Integer[]{1,2,3,4,56});
        return "index";
    }
}

测试:

 3.2取出数组中的对象

index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
2)取出对象中的元素(对象必须被public修饰)
<#list users as a>
    <br>${a.id}:${a.name}
</#list>
</body>
</html>

User实体类:

package com.zq.springboot04.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author张强
 * @site www.zq.com
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
}

ViemController:

package com.zq.springboot04.controller;

import com.zq.springboot04.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;

/**
 * @author张强
 * @site www.zq.com
 */
@Controller
public class ViemController {
    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("users", Arrays.asList(new User(1,"zs"),new User(2,"ls"),new User(3,"ww")));
        return "index";
    }
}

测试:

4、include指令&局部变量&全局变量的用法:

我们假设include一个头部标签,我们先在templates下创建文件head.ftl

head.ftl:

<#--局部变量-->
<#assign ctx>
    ${springMacroRequestContext.contextPath}
</#assign>


<#--全局变量-->
<#global ctx2>
    ${springMacroRequestContext.contextPath}
</#global>

index.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<h3>include指令</h3>
<#include '/head.ftl'>
<h3>局部变量全局变量</h3>
${ctx}:${ctx2}

</body>
</html>

因为我们设置的两个变量都是访问的路径所以为了测试效果,我们改一下访问路径:

测试:

三、Freemarker综合案例

接下来我们做一个Freemarker的案例参考ssm项目来完善(springboot支持ssm开发模式)

效果预览:

 小编按照编码逻辑顺序给大家直接上代码:

实体类Clazz:

package com.zq.springboot04.model;

public class Clazz {
    protected Integer cid;

    protected String cname;

    protected String cteacher;

    protected String pic;

    public Clazz(Integer cid, String cname, String cteacher, String pic) {
        this.cid = cid;
        this.cname = cname;
        this.cteacher = cteacher;
        this.pic = pic;
    }

    public Clazz() {
        super();
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getCteacher() {
        return cteacher;
    }

    public void setCteacher(String cteacher) {
        this.cteacher = cteacher;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }
}

ClazzMapper:

package com.zq.springboot04.mapper;

import com.zq.springboot04.model.Clazz;
import org.springframework.stereotype.Repository;

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

@Repository
public interface ClazzMapper {
    int deleteByPrimaryKey(Integer cid);

    int insert(Clazz record);

    int insertSelective(Clazz record);

    Clazz selectByPrimaryKey(Integer cid);

    List<Clazz> listPager(Clazz clazz);

    List<Map> listMapPager(Clazz clazz);

    int updateByPrimaryKeySelective(Clazz record);

    int updateByPrimaryKey(Clazz record);
}

ClazzMapper.xml:

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zq.springboot04.mapper.ClazzMapper" >
  <resultMap id="BaseResultMap" type="com.zq.springboot04.model.Clazz" >
    <constructor >
      <idArg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="cname" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="cteacher" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="pic" jdbcType="VARCHAR" javaType="java.lang.String" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    cid, cname, cteacher, pic
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_struts_class
    where cid = #{cid,jdbcType=INTEGER}
  </select>

  <select id="listMapPager" resultType="java.util.Map" parameterType="com.zq.springboot04.model.Clazz" >
    select
    <include refid="Base_Column_List" />
    from t_struts_class
    <where>
      <if test="cname != null and cname != ''">
         and cname like CONCAT('%',#{cname},'%')
      </if>
      <if test="cid != null and cid != ''">
        and cid = #{cid}
      </if>
    </where>
  </select>

  <select id="listPager" resultType="com.zq.springboot04.model.Clazz" parameterType="com.zq.springboot04.model.Clazz" >
    select
    <include refid="Base_Column_List" />
    from t_struts_class
    <where>
      <if test="cname != null and cname != ''">
        and cname like CONCAT('%',#{cname},'%')
      </if>
      <if test="cid != null and cid != ''">
        and cid = #{cid}
      </if>
    </where>
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_struts_class
    where cid = #{cid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.zq.springboot04.model.Clazz" >
    insert into t_struts_class (cid, cname, cteacher, 
      pic)
    values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR}, 
      #{pic,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.zq.springboot04.model.Clazz" >
    insert into t_struts_class
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="cid != null" >
        cid,
      </if>
      <if test="cname != null" >
        cname,
      </if>
      <if test="cteacher != null" >
        cteacher,
      </if>
      <if test="pic != null" >
        pic,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="cid != null" >
        #{cid,jdbcType=INTEGER},
      </if>
      <if test="cname != null" >
        #{cname,jdbcType=VARCHAR},
      </if>
      <if test="cteacher != null" >
        #{cteacher,jdbcType=VARCHAR},
      </if>
      <if test="pic != null" >
        #{pic,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zq.springboot04.model.Clazz" >
    update t_struts_class
    <set >
      <if test="cname != null" >
        cname = #{cname,jdbcType=VARCHAR},
      </if>
      <if test="cteacher != null" >
        cteacher = #{cteacher,jdbcType=VARCHAR},
      </if>
      <if test="pic != null" >
        pic = #{pic,jdbcType=VARCHAR},
      </if>
    </set>
    where cid = #{cid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zq.springboot04.model.Clazz" >
    update t_struts_class
    set cname = #{cname,jdbcType=VARCHAR},
      cteacher = #{cteacher,jdbcType=VARCHAR},
      pic = #{pic,jdbcType=VARCHAR}
    where cid = #{cid,jdbcType=INTEGER}
  </update>
</mapper>

ClazzBiz:

package com.zq.springboot04.biz;

import com.zq.springboot04.model.Clazz;
import com.zq.springboot04.util.PageBean;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;

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

public interface ClazzBiz {
    @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    int deleteByPrimaryKey(Integer cid);

    int insert(Clazz record);

    int insertSelective(Clazz record);

//    xx=cache-cid:1
//    key的作用改变原有的key生成规则
//    @Cacheable(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    @CachePut(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    Clazz selectByPrimaryKey(Integer cid);

    int updateByPrimaryKeySelective(Clazz record);

    int updateByPrimaryKey(Clazz record);

    List<Clazz> listPager(Clazz clazz, PageBean pageBean);
    List<Map> listMapPager(Clazz clazz, PageBean pageBean);
}

ClazzBizImpl:

package com.zq.springboot04.biz.impl;

import com.zq.springboot04.biz.ClazzBiz;
import com.zq.springboot04.mapper.ClazzMapper;
import com.zq.springboot04.model.Clazz;
import com.zq.springboot04.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ClazzBizImpl implements ClazzBiz {
    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public int deleteByPrimaryKey(Integer cid) {
        return clazzMapper.deleteByPrimaryKey(cid);
    }

    @Override
    public int insert(Clazz record) {
        return clazzMapper.insert(record);
    }

    @Override
    public int insertSelective(Clazz record) {
        return clazzMapper.insertSelective(record);
    }

    @Override
    public Clazz selectByPrimaryKey(Integer cid) {
        return clazzMapper.selectByPrimaryKey(cid);
    }

    @Override
    public int updateByPrimaryKeySelective(Clazz record) {
        return clazzMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Clazz record) {
        return clazzMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Clazz> listPager(Clazz clazz, PageBean pageBean) {
        return clazzMapper.listPager(clazz);
    }

    @Override
    public List<Map> listMapPager(Clazz clazz, PageBean pageBean) {
        if(true)
            throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.list。。。。");
        return clazzMapper.listMapPager(clazz);
    }
}

ClazzController:

package com.zq.springboot04.controller;

import com.zq.springboot04.biz.ClazzBiz;
import com.zq.springboot04.model.Clazz;
import com.zq.springboot04.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/clz")
public class ClazzController {
    @Autowired
    private ClazzBiz clazzBiz;
    //    list->clzList
//    toList->重定向list->"redirect:/clz/list"
//    toEdit->跳转到编辑界面->clzEdit
//    Clazz : 以前是通过模型驱动接口封装,现在是直接在方法中接受参数即可
    @RequestMapping("/list")
    public String list(Clazz clazz, HttpServletRequest request){
        System.out.println("我添加了 新的代码,终于不重启了....");
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
        request.setAttribute("lst",lst);
        request.setAttribute("pageBean",pageBean);
        //调用分页工具类
        request.setAttribute("pagehepr",FreemarkerPageHelper.toHTML(pageBean));
        return "clz/clzList";
    }

    @RequestMapping("/toEdit")
    public String toEdit(Clazz clazz, HttpServletRequest request){
        Integer cid = clazz.getCid();
//        传递的id代表了修改,没传代表新增
        if(cid != null){
            List<Clazz> lst = this.clazzBiz.listPager(clazz, null);
            request.setAttribute("b",lst.get(0));
        }
        return "clz/clzEdit";
    }

    @RequestMapping("/add")
    public String add(Clazz clazz){
        this.clazzBiz.insertSelective(clazz);
        return "redirect:/clz/list";
    }

    /**
     * @Valid 是与实体类中 的服务端校验 注解配合使用的
     * BindingResult 存放了所有违背 校验的错误信息
     * @param clazz
     * @param bindingResult
     * @return
     */
    @RequestMapping("/valiAdd")
    public String valiAdd(Clazz clazz, BindingResult bindingResult,HttpServletRequest request){
        if (bindingResult.hasErrors()){
            Map msg = new HashMap();
//            违背规则
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
//                cid : cid不能为空
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
//                msg.put(cid,cid不能为空);
                msg.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            request.setAttribute("msg",msg);
//            如果出现了错误,应该将提示语显示在 表单提交元素后方
            return "clzEdit";
        }else {
            this.clazzBiz.insertSelective(clazz);
        }

        return "redirect:/clz/list";
    }

    @RequestMapping("/edit")
    public String edit(Clazz clazz){
        this.clazzBiz.updateByPrimaryKeySelective(clazz);
        return "redirect:/clz/list";
    }

    @RequestMapping("/del")
    public String del(Clazz clazz){
        this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
        return "redirect:/clz/list";
    }

}

做好基础的增删改查代码后,我们来处理分页的问题:

首先我们需要导入分页依赖:

pom: 

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>
    
    <dependency>
       <groupId>com.github.pagehelper</groupId>
       <artifactId>pagehelper-spring-boot-starter</artifactId>
       <version>1.2.3</version>
     </dependency> 

PagerAspect:

package com.zq.springboot04.aspect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zq.springboot04.util.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Aspect
public class PagerAspect {

    /**
     * *:返回值类型
     * *..:无限包
     * *Service:以Service结尾接口名
     * *Pager:以Pager方法
     * 只要同时匹配上诉四个条件,就会被列为目标对象
     * 上述配置要生效,代理注解<aop:aspectj-autoproxy/>不能少
     * @param args
     * @return
     * @throws Throwable
     */
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        Object[] params = args.getArgs();
        PageBean pageBean = null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean = (PageBean)param;
                break;
            }
        }

        if(pageBean != null && pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

//        执行目标方法
        Object list = args.proceed(params);

        if(null != pageBean && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List) list);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return list;
    }


}

然后我们需要整合配置文件:

PageBean:

package com.zq.springboot04.util;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	
	private String url; //保存上一次请求的URL
	
	private Map<String,String[]> paramMap = new HashMap<>();// 保存上一次请求的参数
	
	/**
	 * 初始化pagebean的,保存上一次请求的重要参数
	 * @param req
	 */
	public void setRequest(HttpServletRequest req) {
//		1.1	需要保存上一次请求的URL
		this.setUrl(req.getRequestURL().toString());
//		1.2	需要保存上一次请求的参数	bname、price
		this.setParamMap(req.getParameterMap());
//		1.3	需要保存上一次请求的分页设置	pagination
		this.setPagination(req.getParameter("pagination"));
//		1.4	需要保存上一次请求的展示条目数
		this.setRows(req.getParameter("rows"));
//		1.5  初始化请求的页码	page
		this.setPage(req.getParameter("page"));
	}
	
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page))
			this.setPage(Integer.valueOf(page));
	}

	public void setRows(String rows) {
		if(StringUtils.isNotBlank(rows))
			this.setRows(Integer.valueOf(rows));
	}

	public void setPagination(String pagination) {
//		只有在前台jsp填写了pagination=false,才代表不分页
		if(StringUtils.isNotBlank(pagination))
			this.setPagination(!"false".equals(pagination));
	}


	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, String[]> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, String[]> paramMap) {
		this.paramMap = paramMap;
	}



	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

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

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}
	
	/**
	 * 最大页
	 * @return
	 */
	public int maxPage() {
//		total % rows == 0 ? total / rows : total / rows +1
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int nextPage() {
//		如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1
		return this.page < this.maxPage() ? this.page + 1 : this.page;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int previousPage() {
		return this.page > 1 ? this.page - 1 : this.page;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

}

StringUtils :

package com.zq.springboot04.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

FreemarkerPageHelper:

package com.zq.springboot04.util;

import java.util.Map;
import java.util.Set;

/**
 * @author张强
 * @site www.zq.com
 */
public class FreemarkerPageHelper {
    public static String toHTML(PageBean pageBean) {
        StringBuffer sb = new StringBuffer();
//		隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
//		上一次请求的URL
        sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
        sb.append("	<input type='hidden' name='page'>");
//		上一次请求的参数
        Map<String, String[]> paramMap = pageBean.getParamMap();
        if(paramMap != null && paramMap.size() > 0) {
            Set<Map.Entry<String, String[]>> entrySet = paramMap.entrySet();
            for (Map.Entry<String, String[]> entry : entrySet) {
//				参数名
                String key = entry.getKey();
//				参数值
                for (String value : entry.getValue()) {
//					上一次请求的参数,再一次组装成了新的Form表单
//					注意:page参数每次都会提交,我们需要避免
                    if(!"page".equals(key)) {
                        sb.append("	<input type='hidden' name='"+key+"' value='"+value+"' >");
                    }
                }
            }
        }
        sb.append("</form>");

//		分页条
        sb.append("<ul class='pagination justify-content-center'>");
        sb.append("	<li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");
        sb.append("	href='javascript:gotoPage(1)'>首页</a></li>");
        sb.append("	<li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");
        sb.append("	href='javascript:gotoPage("+pageBean.previousPage()+")'>&lt;</a></li>");// less than 小于号
//		sb.append("	<li class='page-item'><a class='page-link' href='#'>1</a></li>");
//		sb.append("	<li class='page-item'><a class='page-link' href='#'>2</a></li>");
        sb.append("	<li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");
        sb.append("	<li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>&gt;</a></li>");
        sb.append("	<li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");
        sb.append("	<li class='page-item go-input'><b>到第</b><input class='page-link'");
        sb.append("	type='text' id='skipPage' name='' /><b>页</b></li>");
        sb.append("	<li class='page-item go'><a class='page-link'");
        sb.append("	href='javascript:skipPage()'>确定</a></li>");
        sb.append("	<li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
        sb.append("</ul>");

//		分页执行的JS代码
        sb.append("<script type='text/javascript'>");
        sb.append("	function gotoPage(page) {");
        sb.append("		document.getElementById('pageBeanForm').page.value = page;");
        sb.append("		document.getElementById('pageBeanForm').submit();");
        sb.append("	}");
        sb.append("	function skipPage() {");
        sb.append("		var page = document.getElementById('skipPage').value;");
        sb.append("		if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+pageBean.maxPage()+") {");
        sb.append("			alert('请输入1~"+pageBean.maxPage()+"的数字');");
        sb.append("			return;");
        sb.append("		}");
        sb.append("		gotoPage(page);");
        sb.append("	}");
        sb.append("</script>");

        return sb.toString();
    }
}

前端页面clzEdit.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>博客的编辑界面</title>
</head>
<body>
<#include '/head.ftl' />
<#if b??>
<#-- 修改-->
    <form action="${ctx }/clz/edit">
        cid:<input type="text" name="cid" value="${b.cid !}">
        cname:<input type="text" name="cname" value="${b.cname !}">
        cteacher:<input type="text" name="cteacher" value="${b.cteacher !}">
        <input type="submit">
    </form>
<#else>
<#-- 新增 -->
    <form action="${ctx }/clz/add" method="post">
        cid:<input type="text" name="cid" value="">
        cname:<input type="text" name="cname" value="">
        cteacher:<input type="text" name="cteacher" value="">
        <input type="submit">
    </form>
</#if>

</body>
</html>

前端页面clzList.ftl :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link
            href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
            rel="stylesheet">
    <script
            src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    <title>博客列表</title>
    <style type="text/css">
        .page-item input {
            padding: 0;
            width: 40px;
            height: 100%;
            text-align: center;
            margin: 0 6px;
        }

        .page-item input, .page-item b {
            line-height: 38px;
            float: left;
            font-weight: 400;
        }

        .page-item.go-input {
            margin: 0 10px;
        }
    </style>
</head>
<body>
<#include '/head.ftl' />
<#-- 查询条件框  -->
<form class="form-inline"
      action="${ctx}/clz/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="cname"
               placeholder="请输入班级名称">
    </div>
    <button type="submit" class="btn btn-primary mb-2">查询</button>
    <a class="btn btn-primary mb-2" href="${ctx}/clz/toEdit">新增</a>
</form>
<table class="table table-striped bg-success">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">班级名称</th>
        <th scope="col">指导老师</th>
        <th scope="col">班级相册</th>
        <th scope="col">操作</th>
    </tr>
    </thead>
    <tbody>
    <#list lst as b>
        <tr>
            <td>${b.cid !}</td>
            <td>${b.cname !}</td>
            <td>${b.cteacher !}</td>
            <td>
                <a href="${ctx }/clz/toEdit?cid=${b.cid}">修改</a>
                <a href="${ctx }/clz/del?cid=${b.cid}">删除</a>
            </td>
        </tr>
    </#list>
    </tbody>
</table>
${pagehepr !}

</body>
</html>

启动类Springboot04Application:

package com.zq.springboot04;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//完成对mapper接口的扫描
@MapperScan("com.zq.Springboot04.mapper")
//开启事务管理
@EnableTransactionManagement
@SpringBootApplication
public class Springboot04Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot04Application.class, args);
    }

}

配置文件:

mybatis:
    mapper-locations: classpath:mappers/**/*xml
    type-aliases-package: com.zq.springboot04.model
server:
    port: 8080
    servlet:
        context-path: /
spring:
    application:
        name: springboot04
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
        username: root
    freemarker:
        cache: false
        charset: utf-8
        expose-request-attributes: true
        expose-session-attributes: true
        suffix: .ftl
        template-loader-path: classpath:/templates/
    #    resources:
    #        static-locations: classpath:/static/# 应用服务 WEB 访问端口
    mvc:
        static-path-pattern: classpath:/static/

    # 整合分页
    pagehelper:
        reasonable: true
        supportMethodsArguments: true
        page-size-zero: true
        helper-dialect: mysql
    #打印SQL语句
    logging:
        level:
            com.zq.springboot04: debug

测试效果: