Java,FreeMarker,模板引擎,通过案例代码,学懂模板引擎

FreeMarker模板引擎

Apache FreeMarker™ is a template engine,一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 是一个Java类库。

Apache FreeMarker是免费的,基于Apache许可证2.0版本发布。其模板编写为FreeMarker Template Language(FTL),属于简单、专用的语言。

Java,FreeMarker,模板引擎,通过案例代码,学懂模板引擎

Freemarker模板中的数据类型:

1)布尔型:等价于Java的 Boolean 类型,不同的是不能直接输出,可转换为字符串输出;

2)日期型:等价于java的Date类型,不同的是不能直接输出,需要转换成字符串再输出;

3)数值型:等价于java中的 int、float、double等数值类型;

4)有三种显示形式:数值型(默认)、货币型、百分比型;

5)字符型:等价于java中的字符串,有很多内置函数;

6)sequence类型:等价于java中的数组,list,set等集合类型;

7)hash类型:等价于java中的Map类型。

代码案例

pom.xml

<!-- freemarker-->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
    <scope>compile</scope>
</dependency>

案例1:

package com.what21.freemarker01.demo01;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Demo01Main {

    public static void main(String[] args) throws Exception {
        String home = Demo01Main.class.getResource("").getPath();
        System.out.println("home=" + home);
        // 配置
        Configuration configuration =new Configuration(Configuration.getVersion());
        configuration.setDirectoryForTemplateLoading(new File(home));
        configuration.setDefaultEncoding("utf-8");
        // 加载一个模版文件,创建一个模版对象
        Template template =configuration.getTemplate("demo01.ftl");
        // 数据对象
        DataModel dataModel = new DataModel();
        dataModel.setUser("用户");
        Map<String,Object> product = new HashMap<>();
        product.put("url","https://www.toutiao.com/");
        product.put("name","今日头条——小奋斗");
        dataModel.setProduct(product);
        Writer writer = new PrintWriter(System.out);
        template.process(dataModel,writer);
    }

}
package com.what21.freemarker01.demo01;

import java.util.Map;

public class DataModel {

    private String user;

    private Map<String,Object> product;

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public Map<String, Object> getProduct() {
        return product;
    }

    public void setProduct(Map<String, Object> product) {
        this.product = product;
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Welcome!</title>
</head>
<body>
    <h1>Welcome ${user}!</h1>
    <p>Our latest product:
        <a href="${product.url}">${product.name}</a>!
    </p>
</body>
</html>

案例2:

package com.what21.freemarker01.demo02;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;

public class Demo02Main {

    public static void main(String[] args) throws Exception {
        String home = Demo02Main.class.getResource("").getPath();
        System.out.println("home=" + home);
        // 配置
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDirectoryForTemplateLoading(new File(home));
        configuration.setDefaultEncoding("utf-8");
        // 加载一个模版文件,创建一个模版对象
        Template template = configuration.getTemplate("demo02.ftl");
        // 数据对象
        Student student = new Student();
        student.setId(1);
        student.setName("小奋斗");
        student.setAge(32);
        student.setAddress("山西太原");
        DataModel dataModel = new DataModel();
        dataModel.setStudent(student);
        Writer writer = new PrintWriter(System.out);
        template.process(dataModel, writer);
    }

}
package com.what21.freemarker01.demo02;

import lombok.Data;

@Data
public class DataModel {

    private Student student;

}
package com.what21.freemarker01.demo02;

import lombok.Data;

@Data
public class Student {

    private Integer id;

    private String name;

    private int age;

    private String address;

}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>学生信息</title>
    </head>
    <body>
        <h1>学生信息</h1>
        <br />
        <table>
            <tr>
                <td>id</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>地址</td>
            </tr>
            <tr>
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.address}</td>
            </tr>
        </table>
    </body>
</html>

案例3:

package com.what21.freemarker01.demo03;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Demo03Main {

    public static void main(String[] args) throws Exception {
        String home = Demo03Main.class.getResource("").getPath();
        System.out.println("home=" + home);
        // 配置
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDirectoryForTemplateLoading(new File(home));
        configuration.setDefaultEncoding("utf-8");
        // 加载一个模版文件,创建一个模版对象
        Template template = configuration.getTemplate("demo03.ftl");
        // 数据对象
        List<Student> studentList = new ArrayList<>();
        Student student1 = new Student();
        student1.setId(1);
        student1.setName("舜");
        student1.setAge(31);
        student1.setAddress("畎亩之中");
        studentList.add(student1);
        Student student2 = new Student();
        student2.setId(2);
        student2.setName("傅说");
        student2.setAge(33);
        student2.setAddress("版筑之间");
        studentList.add(student2);
        Student student3 = new Student();
        student3.setId(3);
        student3.setName("胶鬲");
        student3.setAge(33);
        student3.setAddress("鱼盐之中");
        studentList.add(student3);
        Student student4 = new Student();
        student4.setId(4);
        student4.setName("管夷吾");
        student4.setAge(34);
        student4.setAddress("士");
        studentList.add(student4);
        DataModel dataModel = new DataModel();
        dataModel.setDate(new Date());
        dataModel.setStudentList(studentList);
        Writer writer = new PrintWriter(System.out);
        template.process(dataModel, writer);
    }

}
package com.what21.freemarker01.demo03;

import lombok.Data;

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

@Data
public class DataModel {

    private List<Student> studentList;

    private Date date;

}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>学生信息</title>
    </head>
    <body>
        <h1>学生信息</h1>
        <br />
        <#if date??>
            <h2>时间:${date?string("dd-MM-yyyy HH:mm:ss")}</h2>
        </#if>
        <table>
            <tr>
                <td>id</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>地址</td>
            </tr>
            <#list studentList as student>
            <#if student_index % 2 ==0>
                <tr bgcolor="red">
            <#else>
                <tr bgcolor="yellow">
            </#if>
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.address}</td>
            </tr>
            </#list>
        </table>
    </body>
</html>

案例4:

package com.what21.freemarker02.demo01;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Demo01Main {

    public static void main(String[] args) throws Exception {
        String home = Demo01Main.class.getResource("").getPath();
        System.out.println("home=" + home);
        // 配置
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDirectoryForTemplateLoading(new File(home));
        configuration.setDefaultEncoding("utf-8");
        // 加载一个模版文件,创建一个模版对象
        Template template = configuration.getTemplate("demo01.ftl");
        // 数据对象
        Map<String, Object> dataModel = new HashMap<>();
        // 布尔类型
        dataModel.put("flag", true);
        // 日期类型  new Data()表示获取现在电脑的时间
        dataModel.put("createDate", new Date());
        // 数值类型
        dataModel.put("age", 18);
        dataModel.put("salary", 10000);
        dataModel.put("avg", 0.545);
        //
        dataModel.put("msg1", "Hello ");
        dataModel.put("msg2", "freemarker");
        Writer writer = new PrintWriter(System.out);
        template.process(dataModel, writer);
    }

}
<!DOCTYPE html>
<html>
<head>
    <title>Welcome!</title>
</head>
<body>
    <table>
        <tr>
            <td>
                ${flag?c}<br>
                ${flag?string}<br>
                ${flag?string("yes","no")}<br>
            </td>
        </tr>
        <tr>
            <td>
                <#-- 输出日期格式 -->
                ${createDate?date} <br>
                <#-- 输出时间格式 -->
                ${createDate?time} <br>
                <#-- 输出日期时间格式 -->
                ${createDate?datetime} <br>
                <#-- 输出格式化日期格式 -->
                ${createDate?string("yyyy年MM月dd日 HH:mm:ss")} <br>
            </td>
        </tr>
        <tr>
            <td>
                <#-- 直接输出数值型 -->
                ${age} <br>
                ${salary} <br>
                <#-- 将数值转换成字符串输出 -->
                ${salary?c} <br>
                <#-- 将数值转换成货币类型的字符串输出 -->
                ${salary?string.currency} <br>
                <#-- 将数值转换成百分比类型的字符串输出 -->
                ${avg?string.percent} <br>
                <#-- 将浮点型数值保留指定小数位输出 (##表示保留两位小数) -->
                ${avg?string["0.##"]} <br>
            </td>
        </tr>
        <tr>
            <td>
                <#-- 直接输出 -->
                ${msg1} - ${msg2} <br>
                ${msg1?string} - ${msg2?string} <br>
                <#-- 1. 截取字符串(左闭右开) ?substring(start,end) -->
                ${msg2?substring(1,4)} <br>
                <#-- 2. 首字母小写输出 ?uncap_first -->
                ${msg1?uncap_first} <br>
                <#-- 3. 首字母大写输出 ?cap_first -->
                ${msg2?cap_first} <br>
                <#-- 4. 字母转小写输出 ?lower_case -->
                ${msg1?lower_case} <br>
                <#-- 5. 字母转大写输出 ?upper_case -->
                ${msg1?upper_case} <br>
                <#-- 6. 获取字符串长度 ?length -->
                ${msg1?length} <br>
                <#-- 7. 是否以指定字符开头(boolean类型) ?starts_with("xx")?string -->
                ${msg1?starts_with("H")?string} <br>
                <#-- 8. 是否以指定字符结尾(boolean类型) ?ends_with("xx")?string -->
                ${msg1?ends_with("h")?string} <br>
                <#-- 9. 获取指定字符的索引 ?index_of("xxx") -->
                ${msg1?index_of("e")} <br>
                <#-- 10. 去除字符串前后空格 ?trim -->
                ${msg1?trim?length} <br>
                <#-- 11. 替换指定字符串 ?replace("xx","xxx") -->
                ${msg1?replace("o","a")}<br>
            </td>
        </tr>
        <tr>
            <td>
                <#-- 如果值不存在,直接输出会报错 -->
                <#--${str}-->
                <#-- 使用!,当值不存在时,默认显示空字符串 -->
                ${str!}<br>
                <#-- 使用!"xx",当值不存在时,默认显示指定字符串 -->
                ${str!"这是一个默认值"}<br>
                <#-- 使用??,判断字符串是否为空;返回布尔类型。如果想要输出,需要将布尔类型转换成字符串 -->
                ${(str??)?string}<br>
            </td>
        </tr>
    </table>
</body>
</html>

案例5:

package com.what21.freemarker02.demo02;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.*;

// sequence 类型
public class Demo02Main {

    public static void main(String[] args) throws Exception {
        String home = Demo02Main.class.getResource("").getPath();
        System.out.println("home=" + home);
        // 配置
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDirectoryForTemplateLoading(new File(home));
        configuration.setDefaultEncoding("utf-8");
        // 加载一个模版文件,创建一个模版对象
        Template template = configuration.getTemplate("demo02.ftl");
        // 数据对象
        Map<String, Object> dataModel = new HashMap<>();
        // 序列类型 (数组、List、Set)
        // 数组操作
        String[] stars = new String[]{"舜", "孙叔敖", "百里奚"};
        dataModel.put("stars", stars);
        // List操作
        List<String> citys = Arrays.asList("上海", "北京", "杭州", "太原");
        dataModel.put("cityList", citys);
        // JavaBean集合
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "舜", 22));
        userList.add(new User(2, "孙叔敖", 18));
        userList.add(new User(3, "百里奚", 20));
        dataModel.put("userList", userList);

        // hash 类型
        Map<String,String> cityMap = new HashMap<>();
        cityMap.put("sh","上海");
        cityMap.put("bj","北京");
        cityMap.put("sz","深圳");
        dataModel.put("cityMap",cityMap);
        Writer writer = new PrintWriter(System.out);
        template.process(dataModel, writer);
    }

}
package com.what21.freemarker02.demo02;

import lombok.Data;

@Data
public class User {

    private int id;
    private String name;
    private int age;

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

}
<!DOCTYPE html>
<html>
<head>
    <title>Welcome!</title>
</head>
<body>
    <table>
        <tr>
            <td>
                <#--
                    数据类型:序列类型 (数组、List、Set)
                        通过list指令输出序列
                            <#list 序列名 as 元素名>
                                ${名称}
                            </#list>
                        获取序列的长度 ${序列名?size}
                        获取序列元素的下标 ${元素名?index}
                        获取第一个元素 ${序列名?first}
                        获取最后一个元素 ${序列名?last}
                        倒序输出 序列名?reverse
                        升序输出 序列名?sort
                        降序输出 序列名?sort?reverse
                        指定字段名排序 序列名?sort_by("字段名")
                            注:一般是JavaBean集合,对应的字段名需要提供get方法
                -->
                <#-- 数组操作 -->
                <#list stars as star>
                    下标:${star?index} -- 名字:${star} <br>
                </#list>
                数组的长度:${stars?size} <br>
                <#-- 获取第一个元素 -->
                第一个元素:${stars?first} <br>
                <#-- 获取最后一个元素 -->
                最后一个元素:${stars?last} <br>
                <hr>
                <#-- List操作 -->
                <#list cityList as city >
                    ${city} <br>
                </#list>
                List的size:${cityList?size} <br>
                <#-- 倒序输出 -->
                <#list cityList?reverse as city >
                    ${city} -
                </#list>
                <#-- 升序输出 -->
                <#list cityList?sort as city >
                    ${city} -
                </#list>
                <br>
                <#-- 降序输出 -->
                <#list cityList?sort?reverse as city >
                    ${city} -
                </#list>
                <hr>
                <#-- JavaBean集合 -->
                <#list userList as user>
                    编号:${user.id}  
                    姓名:${user.name}  
                    年龄:${user.age}  
                    <br>
                </#list>
                <#-- 按照指定字段名排序 -->
                <#list userList?sort_by("age") as user>
                    ${user.name} |
                </#list>
            </td>
        </tr>
        <tr>
            <td>
                <#--
                    数据类型:hash类型
                        key遍历输出
                            <#list hash?keys as key>
                                ${key} -- ${hash[key]}
                            </#list>
                        value遍历输出
                            <#list hash?values as value>
                                ${value}
                            </#list>
                -->
                <#-- key遍历输出 -->
                <#list cityMap?keys as key>
                    ${key} -- ${cityMap[key]} <br>
                </#list>
                <#-- value遍历输出 -->
                <#list cityMap?values as value>
                    ${value} |
                </#list>
            </td>
        </tr>
    </table>
</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至22018681@qq.com 举报,一经查实,本站将立刻删除。

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
森林服务号的头像森林服务号
上一篇 2021年11月23日
下一篇 2021年11月23日

相关推荐

发表回复

登录后才能评论