http://blog.csdn.net/marksinoberg/article/details/52006311

***************************************************

今天分享一下一个模板语言的使用,它就是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();
} } }
  • 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
  • 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

案例分析一

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

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试</title>
</head> <body>
<h1>你好${username}</h1>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

测试代码如下:

/**
* 仅仅针对有一个数据的测试
*
* @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));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

案例分析二

使用到的模板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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

我们可以从模板中看到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 + "]";
} }
  • 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
  • 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

内有组合类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 + "]";
} }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

测试代码如下:

/**
* 控制台输出带有对象的模板使用案例
*
* @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));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
/**
* 输出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");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

案例分析三

使用到的模板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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

测试代码如下:

/**
* 输出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");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

案例分析四

使用到的模板文件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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

测试代码如下:

@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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

程序运行结果浏览

Freemarker 浅析 (zhuan)的更多相关文章

  1. Freemarker 浅析

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

  2. Freemarker 入门示例(zhuan)

    http://cuisuqiang.iteye.com/blog/2031768 ************************************ 初步学习freemarker ,先做一个简单 ...

  3. Velocity浅析及与Jsp、Freemarker对比

    转载自:http://www.cnblogs.com/petermsdn/archive/2011/05/06/2039178.html Velocity 是一个基于java 的模板引擎(templa ...

  4. Velocity浅析及与Jsp、Freemarker对比 分类: B1_JAVA 2014-07-21 09:14 637人阅读 评论(0) 收藏

    转载自:http://www.cnblogs.com/petermsdn/archive/2011/05/06/2039178.html Velocity 是一个基于java 的模板引擎(templa ...

  5. GreenDao开源ORM框架浅析

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u011133213/article/details/37738943 Android程序开发中,避免 ...

  6. SQL Server on Linux 理由浅析

    SQL Server on Linux 理由浅析 今天的爆炸性新闻<SQL Server on Linux>基本上在各大科技媒体上刷屏了 大家看到这个新闻都觉得非常震精,而美股,今天微软开 ...

  7. 【深入浅出jQuery】源码浅析--整体架构

    最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...

  8. 高性能IO模型浅析

    高性能IO模型浅析 服务器端编程经常需要构造高性能的IO模型,常见的IO模型有四种: (1)同步阻塞IO(Blocking IO):即传统的IO模型. (2)同步非阻塞IO(Non-blocking  ...

  9. netty5 HTTP协议栈浅析与实践

      一.说在前面的话 前段时间,工作上需要做一个针对视频质量的统计分析系统,各端(PC端.移动端和 WEB端)将视频质量数据放在一个 HTTP 请求中上报到服务器,服务器对数据进行解析.分拣后从不同的 ...

随机推荐

  1. Monthly Expense(二分查找)

    Monthly Expense Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 17982 Accepted: 7190 Desc ...

  2. view class source code with JAD plugin in Eclipse

    The default class viewer doesn't decompile the class file so you cannot open and check the source co ...

  3. 从客户端中检测到有潜在危险的 Request.Form 值

    今天在使用Kindeditor的时候,出现了如题的错误. 错误如图: 百度了下,艰难的找了原来是Framework的问题,原来用的2.0,后面变成了4.0,验证级别也更高了: 解决办法:在config ...

  4. HDU 4651 Partition 整数划分,可重复情况

    Partition Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  5. Android ActivityThread(主线程或UI线程)简介

    1. ActivityThread功能 它管理应用进程的主线程的执行(相当于普通Java程序的main入口函数),并根据AMS的要求(通过IApplicationThread接口,AMS为Client ...

  6. Mysql-学习笔记(==》插入修改数据二)

    USE db; -- 建立学生信息表CREATE TABLE student( sno INT UNSIGNED NOT NULL AUTO_INCREMENT, sname VARCHAR(20) ...

  7. HTTP断点续传的基本原理

    转自:http://blog.csdn.net/sendy888/article/details/1719105 断点续传是我们现在经常接触的概念,那么HTTP协议是如何支持断点续传的呢.我们先从一个 ...

  8. 源码安装python

    编译安装新版本python 一般来说python是linux系统的标配,但是版本一般却很老,而系统上面的很多服务可能与老的python存在依赖关系,我们又不能直接卸载.所以一般,我们可以在一个单独的目 ...

  9. centos系统下设置固定IP+dns

    笔者用的linux系统是centos版本的,在次之前linux是空白,今天我在物理机用XSHELL连接虚拟机中的centos时候出现连接失败的情况,我的第一反应就是IP是不是变了?打开虚拟机之后在终端 ...

  10. PHP 对字符串进行十六进制替换 invalid character in attribute value

    最近在xml传输过程中遇到字符串报错,表面看上去没有任何错误.将文件用winhex打开,看到对应字符串中多了'1F'.xml无法解析'1F'.随后在代码中将这个替换掉. $str = pack(&qu ...