编程随笔 编程随笔
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)

liyao52033

走运时,要想到倒霉,不要得意得过了头;倒霉时,要想到走运,不必垂头丧气。心态始终保持平衡,情绪始终保持稳定,此亦长寿之道
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)
  • springboot

    • MyBatis Plus使用
    • springboot2引入swagger3
    • EasyCaptcha验证码存入redis的使用
    • 常用方法
    • Elasticsearch全文搜索
    • canal同步mysql数据到es中
    • SpringSecurity使用
    • StringUtils 工具类使用
    • HTTP各种参数发送
    • EasyExcel之Excel导入导出
    • EasyExcel具体使用
    • FreeMarker 模板引擎入门
    • FreeMarker生成文件及WEB使用
      • 生成本地文件
      • 通过WEB使用FreeMarker的方式
      • 模板的语法
    • TrueLicense 创建及安装证书
  • 服务器相关

  • 腾讯云cos对象操作

  • 后端
  • springboot
华总
2023-11-23
0
0
目录

FreeMarker生成文件及WEB使用原创

# 生成本地文件

  1. 创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
  2. 设置模板文件所在的路径。
  3. 设置模板文件使用的字符集。一般就是utf-8.
  4. 加载一个模板,创建一个模板对象。
  5. 创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
  6. 创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
  7. 调用模板对象的process方法输出文件。
  8. 关闭流.

示例模板index.ftl如下

<!DOCTYPE html>
<html lang="">
<head>
  <meta charset="utf-8">
  <title>Hello World!</title>
</head>
<body>
<b>普通文本 String 展示:</b><br><br>
Hello ${name} <br>
<hr>
<b>对象Student中的数据展示:</b><br/>
姓名:${stu.name}<br/>
年龄:${stu.age}
<hr>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

业务层代码如下

/**
 * FreeMarker一般的使用方式 示例
 */
@SpringBootTest
public class NormalTests {

    @Test
     public void test() throws IOException, TemplateException {

        String templateDir =  String templateDir = "src/main/resources/templates/";

        // -> 获取FreeMarker配置实例
        Configuration conf = new Configuration(Configuration.VERSION_2_3_32);

        // -> 指定模板文件所在文件夹
        // 直接指明文件夹路径的方式
         conf.setDirectoryForTemplateLoading(new File(templateDir));
        // 通过类加载器,使用相对路径的方式
        // conf.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "/templates/");

        // -> 设置编码(注:如果不设置或设置错了此项的话,那么加载模板的时候,可能导致中文乱码)
        conf.setDefaultEncoding("utf-8");

        // -> 获取ftl模板
        Template template = conf.getTemplate("index.ftl");

        // -> 准备数据数据
        Map<String, Object> root = new HashMap<>(8);
        // 注意:因为freemarker模板会试着解析key,所以key命名时不要有敏感词汇;如:这里key取的是【root-key】的话,那么就会出错
       Map<String, Object> root = new HashMap<>(8);
       root.put("name","小舞");
       //实体类
       Student student = new Student();
       student.setAge(22);
       student.setName("张三");
       student.setBirthday(new Date());
       root.put("stu",student);

        // -> 准备输出流
        // 此方式可能导致输出时中文乱码
        // Writer out = new FileWriter(new File("E:/demo/templates/normal.html"));
        // 此方式可保证输出时中文不乱码
       Writer out =
                new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(new File(templateDir + "index.html").toPath()),
                        StandardCharsets.UTF_8));
       
        // -> 数据 + 输出流 = 生成的文件
        template.process(root, out);

        // -> 释放资源
        out.flush();
        out.close();
    }
}
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

# 通过WEB使用FreeMarker的方式

关键点说明

  • 给控制层方法额外加一个SpringMVC数据处理模型(Model或ModelMap或Map)。 注:对于那些请求本身就带有参数的方法,只需要额外加数据处理模型即可,不影响原参数的获取。
  • 方法返回值为String,返回模板文件(相对于spring.freemarker.template-loader-path参数指定的文件夹)的文件名路径(不要后缀)。

# 无参请求的使用方式

/**
 * FreeMarker使用示例
 */
@Controller
public class DemoController {

    private static final int LIMIT_MAX = 5;

    /**
     * FreeMarker常用语法示例
     *
     * @param model
     *            SpringMVC 数据模型
     *
     * @return  (无后缀的)模板文件名
     *          注:模板文件所在根目录在配置文件
     */
    @GetMapping("/grammar/demo")
    public String demoMethod(Model model) {

        // 直接取值示例
        model.addAttribute("testOne", "邓沙利文");

        // 获取对象属性值示例
        User testTwoUser = User.builder()
                               .name("邓二洋")
                               .age(25)
                               .gender("男")
                               .hobby("女")
                               .motto("我是一只小小小小鸟~")
                               .build();
        model.addAttribute("testTwo", testTwoUser);

        // if示例
        User testThreeUser = User.builder().name("邓沙利文").age(25).build();
        model.addAttribute("testThree", testThreeUser);

        // list 示例
        List<User> testFourList = new ArrayList<>(8);
        for (int i = 0; i < LIMIT_MAX; i++) {
            User u = User.builder().name("邓" + i + "洋" ).motto("我是一只小小小小鸟~").build();
            testFourList.add(u);
        }
        model.addAttribute("testFourList", testFourList);

        // map示例
        Map<String, User> testFiveMap = new HashMap<>(8);
        for (int i = 0; i < LIMIT_MAX; i++) {
            User tempUser = User.builder().name("邓" + i + "洋" ).motto("我是一只小小小小鸟~").build();
            testFiveMap.put("key" + i, tempUser);
        }
        model.addAttribute("testFiveMap", testFiveMap);

        // 日期示例
        model.addAttribute("myDate", new Date());
        return "abc/grammar_demo";
    }

    /**
     * 以以下三种中的任意一种模型来封装数据,都是会被FreeMarker解析到的
     *
     * 1、org.springframework.ui.Model
     *
     * 2、org.springframework.ui.ModelMap
     *
     * 3、java.uti.Map
     *
     * @param mode
     *            SpringMVC 数据模型
     *
     * @return  (无后缀的)模板文件名
     *          注:模板文件所在根目录在配置文件
     */
    @GetMapping("/model/test1")
    public String modelTestOne(Model mode) {
        mode.addAttribute("xyz", "org.springframework.ui.Model也可以作为参数模型!");
        return "abc/model_test";
    }

    @GetMapping("/model/test2")
    public String modelTestTwo(ModelMap modelMap) {
        modelMap.addAttribute("xyz", "org.springframework.ui.ModelMap也可以作为参数模型!");
        return "abc/model_test";
    }

    @GetMapping("/model/test3")
    public String demoMethodThree(Map<String, Object> map) {
        map.put("xyz", "java.util.Map也可以作为参数模型!");
        return "abc/model_test";
    }
}
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

# 有参请求的使用方式

/**
 * FreeMarker使用示例
 */
@Controller
public class DemoController {

    /**
     * 当方法需要传入参数时的 GET测试
     *
     * @param model
     *            SpringMVC 数据模型
     * @param name
     *            用户传入的参数name
     * @param age
     *            用户传入的参数age
     *
     * @return  (无后缀的)模板文件名
     *          注:模板文件所在根目录在配置文件
     */
    @GetMapping("/hava/param/get/")
    public String paramsTest(Model model, @RequestParam("name") String name, @RequestParam("age")  Integer age) {
        model.addAttribute("myRoot", name + age);
        return "abc/hava_params_test";
    }

    /**
     * 当方法需要传入参数时的 POST测试
     *
     * @param model
     *            SpringMVC 数据模型
     * @param user
     *            用户传入的参数user
     *
     * @return  (无后缀的)模板文件名
     *          注:模板文件所在根目录在配置文件
     */
    @PostMapping("/hava/param/post/")
    public String paramsTest(Model model, @RequestBody User user) {
        model.addAttribute("myRoot", user.getName() + "都特么" + user.getAge() + "岁了!");
        return "abc/hava_params_test";
    }
}
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

# 模板的语法

# 访问map中的key

${key}
1

# 访问pojo中的属性

${classes.classname}
1

# 取集合中的数据

<#list studentList as student> 遍历studentList 每次对象存为student
${student.id}/${studnet.name}
</#list>
1
2
3

# 取循环中的下标

<#list studentList as student>
	${student_index} 注意是_ 不是.
</#list>
1
2
3

# 判断

<#if student_index % 2 == 0>
<#else> 这里面写的和if一致
</#if>
1
2
3

# 日期类型格式化

${date?date}
${date?time}
${date?datetime}
${date?string(parten)}	${date?string("yyyy/MM/dd HH:mm:ss")}
1
2
3
4

# Null值的处理

${val!"val的值为null"} 如果返回true代表没有值
判断val的值是否为null
<#if val??>  这里和上面不一样,如果返回true代表有值
val中有内容
<#else>
val的值为null
</#if>
1
2
3
4
5
6
7

# Include标签

<#include “模板名称”>
1
#后端#springboot#FreeMarker
上次更新: 2023/12/09 16:19:24
FreeMarker 模板引擎入门
TrueLicense 创建及安装证书

← FreeMarker 模板引擎入门 TrueLicense 创建及安装证书→

最近更新
01
element-plus多文件手动上传 原创
11-03
02
TrueLicense 创建及安装证书 原创
10-25
03
手动修改迅捷配置 原创
09-03
04
安装 acme.sh 原创
08-29
05
zabbix部署 原创
08-20
更多文章>
Copyright © 2023-2024 liyao52033
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式