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);
}
程序运行结果浏览
Freemarker 浅析的更多相关文章
- Freemarker 浅析 (zhuan)
http://blog.csdn.net/marksinoberg/article/details/52006311 ***************************************** ...
- Velocity浅析及与Jsp、Freemarker对比
转载自:http://www.cnblogs.com/petermsdn/archive/2011/05/06/2039178.html Velocity 是一个基于java 的模板引擎(templa ...
- 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 ...
- GreenDao开源ORM框架浅析
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u011133213/article/details/37738943 Android程序开发中,避免 ...
- SQL Server on Linux 理由浅析
SQL Server on Linux 理由浅析 今天的爆炸性新闻<SQL Server on Linux>基本上在各大科技媒体上刷屏了 大家看到这个新闻都觉得非常震精,而美股,今天微软开 ...
- 【深入浅出jQuery】源码浅析--整体架构
最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...
- 高性能IO模型浅析
高性能IO模型浅析 服务器端编程经常需要构造高性能的IO模型,常见的IO模型有四种: (1)同步阻塞IO(Blocking IO):即传统的IO模型. (2)同步非阻塞IO(Non-blocking ...
- netty5 HTTP协议栈浅析与实践
一.说在前面的话 前段时间,工作上需要做一个针对视频质量的统计分析系统,各端(PC端.移动端和 WEB端)将视频质量数据放在一个 HTTP 请求中上报到服务器,服务器对数据进行解析.分拣后从不同的 ...
- spring源码分析之freemarker整合
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户的,而是一个Java类库,是一款程 ...
随机推荐
- cd
从当前目录切换到目标目录 cd [目标目录] 切换到用户主目录 cd cd~ 切换到根目录 cd / 切换到上级目录 cd .. cd ../ cd ..// 切换到上级目录的父目录 ...
- Random Forest vs GradientBoostingDecisionTree
相同 随机森林和GBDT都属于集成算法,base model都是决策树. 不同 随机森林 随机森林是决策树的bagging. bagging通过重复对原训练数据集上进行有放回地采样生成的数据集用bas ...
- JDBC查询优化,统计条数
JDBC查询优化分析: 现有以下查询语句: String sql1 = "select * from userinfo";// 创建语句 String sql2 = "s ...
- [HNOI 2015]接水果
Description 风见幽香非常喜欢玩一个叫做 osu!的游戏,其中她最喜欢玩的模式就是接水果. 由于她已经DT FC 了The big black, 她觉得这个游戏太简单了,于是发明了一个更 ...
- [CQOI2010]内部白点
Description 无限大正方形网格里有n个黑色的顶点,所有其他顶点都是白色的(网格的顶点即坐标为整数的点,又称整点).每秒钟,所有内部白点同时变黑,直到不存在内部白点为止.你的任务是统计最后网格 ...
- ●BZOJ 1969 [Ahoi2005]LANE 航线规划
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=1969 题解: 线段树,树链剖分,反向考虑思路是很巧妙,但是感觉代码真的恶心.. 反着考虑,先 ...
- HDU 4641 K-string
Description Given a string S. K-string is the sub-string of S and it appear in the S at least K time ...
- hdu 5656 CA Loves GCD(n个任选k个的最大公约数和)
CA Loves GCD Accepts: 64 Submissions: 535 Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 2 ...
- Python中编码的详细讲解
看这篇文章前,你应该已经知道了为什么有编码,以及编码的种类情况 ASCII 占1个字节,只支持英文 GB2312 占2个字节,支持6700+汉字 GBK GB2312的升级版,支持21000+汉字 S ...
- Automap sqlalchemy.ext.automap 自动映射数据库表结构
from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy i ...