当前位置: 首页 > news >正文

Freemarker 浅析

今天分享一下一个模板语言的使用,它就是Freemarker,有点类似与前些日子做Python的Django中的模板语言,其实原理上都是相似的。所以这里就不对那些基础性的语法类的直至进行讲解了,就拿几个实用的小例子来分析分析。


依赖

我们需要导入一个jar包,名为freemarker.jar。随便到网上下载一个就行,而且对其他诸如servlet等没有依赖,所以我们可以很轻松的进行移植操作。

工具类FreemarkerUtil.java

package main;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Map;

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

public class FreemarkerUtil {

    /**
     * 根据给定的ftl(freemarker template language)来获得一个用于操作的模板
     * @param name
     * @return
     */
    public Template getTemplate(String name) {
        try {
            // 通过Freemark而的Configuration读取到相应的模板ftl
            Configuration cfg = new Configuration();
            // 设定去哪里读取相关的模板FTL文件
            cfg.setClassForTemplateLoading(this.getClass(), "/ftl");
            // 在模板文件目录中找到名为name的文件
            Template template = cfg.getTemplate(name);
            return template != null ? template : null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过控制台输出文件信息
     * 
     * @param name
     * @param root
     */
    public void print(String name, Map<String, Object> root) {
        try {
            // 通过Template可以将模板文件输出到相应的流
            Template template = this.getTemplate(name);
            template.process(root, new PrintWriter(System.out));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 输出为HTML文件
     * 
     * @param name
     * @param root
     * @param outfile
     */
    public void htmlprint(String name, Map<String, Object> root, String outfile) {
        FileWriter writer = null;
        try {
            // 使用一个路径实现将文件的输出
            writer = new FileWriter(new File("src/"+ outfile));
            Template template = this.getTemplate(name);
            template.process(root, writer);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

案例分析一

我使用的第一个简单的模板01.ftl如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试</title>
</head>

<body>
<h1>你好${username}</h1>
</body>
</html>

测试代码如下:

/**
     * 仅仅针对有一个数据的测试
     * 
     * @throws Exception
     */
    @Test
    public void testftl1() throws Exception {
        FreemarkerUtil util = new FreemarkerUtil();
        Template template = util.getTemplate("01.ftl");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", "XIAO MARK");
        // 默认输出到了控制台上
        template.process(map, new OutputStreamWriter(System.out));
    }

案例分析二

使用到的模板03.ftl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${user.id}-----${user.name}-----${user.age}</h1>
<#if user.age lt 12>
    ${user.name}还是一个小孩
<#elseif user.age lt 18>
    ${user.name}快成年
<#else>
    ${user.name}已经成年
</#if>
</body>
</html>

我们可以从模板中看到user.id,那就说明我们使用到了对象,所以UserBean 详情如下。

package main;

import java.io.Serializable;

public class User implements Serializable {

    private int id;
    private String name;
    private int age;
    private Group group;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + ", group=" + group + "]";
    }

}

内有组合类Group的使用,

package main;

import java.io.Serializable;

public class Group implements Serializable{

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Group [name=" + name + "]";
    }

}

测试代码如下:

/**
     * 控制台输出带有对象的模板使用案例
     * 
     * @throws Exception
     */
    @Test
    public void testftl3() throws Exception {
        FreemarkerUtil util = new FreemarkerUtil();
        Template template = util.getTemplate("03.ftl");
        Map<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        user.setId(1);
        user.setName(" 妈的智障 ");
        user.setAge(21);
        map.put("user", user);
        template.process(map, new OutputStreamWriter(System.out));
    }
/**
     * 输出HTML文件形式的带有对象的测试案例
     * 
     * @throws Exception
     */
    @Test
    public void testftl3outtofile() throws Exception {
        FreemarkerUtil util = new FreemarkerUtil();
        Template template = util.getTemplate("03.ftl");
        Map<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        user.setId(1);
        user.setName(" 妈的智障 ");
        user.setAge(21);
        map.put("user", user);
        util.htmlprint("03.ftl", map, "./../page/03ftloutfile.html");
    }

案例分析三

使用到的模板05.ftl如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
<hr/>
<#list users as user>
${user.id}---------${user.name}-------${user.age}<br/>
</#list>
</body>
</html>

测试代码如下:

/**
     * 输出HTML文件形式的带有对象的测试案例
     * 
     * @throws Exception
     */
    @Test
    public void testftl5outtofile() throws Exception {
        FreemarkerUtil util = new FreemarkerUtil();
        Template template = util.getTemplate("03.ftl");
        Map<String, Object> map = new HashMap<String, Object>();
        List<User> users = new ArrayList<User>();
        for (int i = 1; i <= 10; i++) {
            User user = new User();
            user.setId(i);
            user.setName(" 妈的智障 " + (i * i));
            user.setAge((int) (Math.random() * 100));
            users.add(user);
        }
        map.put("users", users);
        util.htmlprint("05.ftl", map, "./../page/05ftloutfile.html");
    }

案例分析四

使用到的模板文件06.ftl如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
${user.id}-------${user.name}------${user.group!}  <#-- !后为空就不输出  -->
<#--${user.group.name!}--><#-- 按照以上的方式加! freemarker仅仅只会判断group.name是不是空值 -->
${(user.group.name)!"1234"} 

${(a.b)!"没有a.b元素"}

<#--
!:指定缺失变量的默认值 
??:判断某个变量是否存在,返回boolean-->
<#if (a.b)??> <#--if后不用加$-->
    不为空
<#else>
    为空
</#if>
</body>
</html>

测试代码如下:

@Test
    public void testftl6() throws Exception {
        FreemarkerUtil util = new FreemarkerUtil();
        Map<String,Object > map = new HashMap<String,Object>();
        User user = new User();
        Group group = new Group();
        group.setName("1234");
        user.setId(28);
        user.setAge(27);
        user.setName("  妈的智障      ");
        user.setGroup(group);
        map.put("user", user);
        util.print("06.ftl", map);
    }

程序运行结果浏览

项目目录

集合形式对象内容遍历

相关文章:

  • [转] C#实现在Sql Server中存储和读取Word文件 (Not Correct Modified)
  • 终极解决方案:windows10开机黑屏,死机
  • C#打印条码BarTender SDK打印之路和离开之路(web平凡之路)
  • 规范化安全开发 KOA 手脚架
  • mysql开启/关闭 update delete 安全模式
  • Bzoj1007 水平可见直线
  • NGINX与APACHE工作模式的区别
  • thymeleaf th:attr标签
  • linux基础(7)-IO重定向
  • 【Xcode command line】命令行工具
  • sql 语句中 idlt ;SELECT * FROM t_blog WHERE idlt;#{id} ORDER BY id DESC LIMIT 1
  • I/O多路转接之select
  • 【Qt笔记】绘制设备
  • gitlab smtp设置
  • C语言小知识,摘自o'reilly著C程序设计新思维,人民邮电出版社
  • Date型的使用
  • ES6简单总结(搭配简单的讲解和小案例)
  • Hexo+码云+git快速搭建免费的静态Blog
  • iOS筛选菜单、分段选择器、导航栏、悬浮窗、转场动画、启动视频等源码
  • JavaScript 基础知识 - 入门篇(一)
  • JavaScript函数式编程(一)
  • JS变量作用域
  • node学习系列之简单文件上传
  • Python socket服务器端、客户端传送信息
  • React-Native - 收藏集 - 掘金
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • vue的全局变量和全局拦截请求器
  • yii2权限控制rbac之rule详细讲解
  • 代理模式
  • 分类模型——Logistics Regression
  • 复杂数据处理
  • 将回调地狱按在地上摩擦的Promise
  • 码农张的Bug人生 - 初来乍到
  • 爬虫模拟登陆 SegmentFault
  • ​批处理文件中的errorlevel用法
  • (待修改)PyG安装步骤
  • (论文阅读40-45)图像描述1
  • (学习日记)2024.02.29:UCOSIII第二节
  • (一)UDP基本编程步骤
  • (转载)微软数据挖掘算法:Microsoft 时序算法(5)
  • .htaccess 强制https 单独排除某个目录
  • .net FrameWork简介,数组,枚举
  • .Net Web窗口页属性
  • .NET国产化改造探索(一)、VMware安装银河麒麟
  • @Responsebody与@RequestBody
  • @RestController注解的使用
  • @zabbix数据库历史与趋势数据占用优化(mysql存储查询)
  • [20170705]diff比较执行结果的内容.txt
  • [BSGS算法]纯水斐波那契数列
  • [C++]拼图游戏
  • [codeforces] 25E Test || hash
  • [docker] Docker容器服务更新与发现之consul
  • [go 反射] 进阶
  • [HTML]Web前端开发技术18(HTML5、CSS3、JavaScript )HTML5 基础与CSS3 应用——喵喵画网页
  • [k8s系列]:kubernetes·概念入门