springboot2.0整合freemarker快速入门

freemarker是一个用Java开发的模板引擎

常用的java模板引擎还有哪些?
JspFreemarkerThymeleafVelocity 等。

1. 快速入门

1.1 创建工程pom.xml文件如下

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2 编辑application.yml

server:
  port: 8088
spring:
  application:
    name: test-freemarker
  #    freemarker配置
  freemarker:
    cache: false  #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0  #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
    template-loader-path: classpath:/templates
    charset: UTF-8
    check-template-location: true
    suffix: .ftl
    content-type: text/html
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request

1.3 创建模型类

freemarker的测试工程下创建模型类型用于测试

package com.example.demo.model;

import lombok.Data;
import lombok.ToString;

import java.util.Date;
import java.util.List;

/**
 * @author john
 * @date 2019/12/20 - 16:52
 */
@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年龄
    private Date birthday;//生日
    private Float money;//钱包
    private List<Student> friends;//朋友列表
    private Student bestFriend;//最好的朋友
}

1.4 创建模板

src/main/resources下创建templates,此目录为freemarker的默认模板存放目录。
templates下创建模板文件test1.ftl,模板中的${name}最终会被freemarker替换成具体的数据。

<html>
<head>
    <title>hello world!</title>
</head>
<body>
hello ${name}
</body>
</html>

1.5 创建controller

package com.example.demo.controller;

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

import java.util.Map;

/**
 * @author john
 * @date 2019/12/20 - 16:54
 */

@Controller
@RequestMapping("freemarker")
public class FreemarkerController {

    @GetMapping("/test1")
    public String freemarker(Map<String, Object> map) {
        map.put("name", "java");
        //返回模板文件名称
        return "test1";
    }
}

1.6 测试

2. FreeMarker 基础

2.1 数据模型

Freemarker静态化依赖数据模型和模板,下边定义数据模型:
下边方法形参map即为freemarker静态化所需要的数据模型,在map中填充数据:

@GetMapping("/test1")
    public String freemarker(Map<String, Object> map) {
        //向数据模型放数据
        map.put("name", "john");
        Student stu1 = new Student();
        stu1.setName("小明");
        stu1.setAge(18);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
        Student stu2 = new Student();
        stu2.setName("小红");
        stu2.setMoney(200.1f);
        stu2.setAge(19);
//        stu2.setBirthday(new Date());
        List<Student> friends = new ArrayList<>();
        friends.add(stu1);
        stu2.setFriends(friends);
        stu2.setBestFriend(stu1);
        List<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);
        //向数据模型放数据
        map.put("stus", stus);
        //准备map数据
        HashMap<String, Student> stuMap = new HashMap<>();
        stuMap.put("stu1", stu1);
        stuMap.put("stu2", stu2);
        //向数据模型放数据
        map.put("stu1", stu1);
        //向数据模型放数据
        map.put("stuMap", stuMap);
        //返回模板文件名称
        return "test1";
    }

2.2 List指令

本节定义freemarker模板,模板中使用freemarker的指令,关于freemarker的指令需要知道:

1、注释,即<#‐‐和‐‐>,介于其之间的内容会被freemarker忽略
2、插值(Interpolation):即${..}部分,freemarker会用真实的值代替${..}
3、FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑。
4、文本,仅文本信息,这些不是freemarker的注释、插值、FTL指令的内容会被freemarker忽略解析,直接输出内
容。

在test1.ftl模板中使用list指令遍历数据模型中的数据:

<html>
<head>
    <title>hello world!</title>
</head>
<body>
<table>
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td>${stu_index + 1}</td>
            <td>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.money}</td>
        </tr>
    </#list>
</table>
</body>
</html>

输出

_index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始

2.3 遍历Map数据

  1. 数据模型
    使用map指令遍历数据模型中的stuMap

  2. 模板

<html>
<head>
    <title>hello world!</title>
</head>
<body>

输出stu1的学生信息:<br/>
姓名:${stuMap.stu1.name}<br/>
年龄:${stuMap.stu1.age}<br/>
遍历输出两个学生信息:<br/>
<table>
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stuMap?keys as k>
        <tr>
            <td>${k_index + 1}</td>
            <td>${stuMap[k].name}</td>
            <td>${stuMap[k].age}</td>
            <td>${stuMap[k].money}</td>
        </tr>
    </#list>
</table>
</body>
</html>

输出结果

2.4 if指令

if 指令即判断指令,是常用的FTL指令,freemarker在解析时遇到if会进行判断,条件为真则输出if中间的内容,否
则跳过内容不再输出。
1、数据模型:
使用list指令中测试数据模型。
2、模板:

<html>
<head>
    <title>hello world!</title>
</head>
<body>
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.money}</td>
        </tr>
    </#list>
</table>
</body>
</html>

2.5 运算符

  • 算数运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , %

  • 逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误

  • 比较运算符 表达式中支持的比较运算符有如下几个:
    • 1 =或者==:判断两个值是否相等.
    • 2 !=:判断两个值是否不等.
    • 3 >或者gt:判断左边值是否大于右边值
    • 4 >=或者gte:判断左边值是否大于等于右边值
    • 5 <或者lt:判断左边值是否小于右边值
    • 6 <=或者lte:判断左边值是否小于等于右边值

注意: =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)>

2.6 空值处理

1、判断某变量是否存在使用 “??” 用法为:variable??,如果该变量存在,返回true,否则返回false

例:为防止stus为空报错可以加上判断如下:

<#if stus??>
        <#list stus as stu>
            <tr>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
        </#list>
    </#if>

2、缺失变量默认值使用 “!” 使用!要以指定一个默认值,当变量为空时显示默认值。

例:${name!''}表示如果name为空显示空字符串。
如果是嵌套对象则建议使用()括起来。

例: ${(stu.bestFriend.name)!''}表示,如果stubestFriendname为空默认显示空字符串。

2.7 内建函数

内建函数语法格式: 变量+?+函数名称

1、和到某个集合的大小

${集合名?size}

<html>
<head>
    <title>hello world!</title>
</head>
<body>
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#if stus??>
        stus集合的大小是${stus?size}
        <#list stus as stu>
            <tr>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
        </#list>
    </#if>
</table>
</body>
</html>

2、日期格式化
显示年月日: ${today?date}
显示时分秒:${today?time}  
显示日期+时间:${today?datetime} <br>       
自定义格式化:  ${today?string("yyyy年MM月")}
<#if stus??>
        <#list stus as stu>
            <tr>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
                <td>${(stu.birthday?date)!''}---${(stu.birthday?time)!''}---${(stu.birthday?datetime)!''}
                    ---${(stu.birthday?string("yyyy年MM月"))!''}</td>
            </tr>
        </#list>
    </#if>

3、内建函数c
map.put("point", 102920122);

point是数字型,使用${point}会显示这个数字的值,不并每三位使用逗号分隔。
如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出
${point?c}

4、将json字符串转成对象

一个例子:
其中用到了 assign标签,assign的作用是定义一个变量。

<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}

猜你喜欢

转载自www.cnblogs.com/ifme/p/12074678.html