月初写了两篇博客,瞅着月末了,发现自己一个写博客的特点:越来越喜欢开门见山,不喜欢拐弯抹角了!!!所以,这里就不说为什么我会学习freemaker了!
一、配置环境
直接将下载的freemarker下的两个文件拷贝到eclipse的主目录下面freemarker下的两个文件:
Features
Plugins
C:\Java\tool\eclipse:
二、开发流程
1)、引入freemarker的jar包:
<dependency><groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
2)、创建相应的ftl模板文件,注意,文件名一定是ftl格式的
src.mian.resource.ftl.hello.ftl
Hello:${username}
src.mian.resource.ftl.hello.ftl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello:${user.userName}</h1>
${user.nicekName}年纪已经${user.age}
</body>
</html>
3)、测试方法
@Test
public void testFHello() {
try {
// 1、创建Configuration
Configuration cfg = new Configuration();
// 2、设置config中加载模板的路径
// 设置了基于classpath加载路径,并且所有的模板文件都放在/ftl中
cfg.setClassForTemplateLoading(TestFreemarker.class, "/ftl");
// 3、获取模板文件,由于已经设置了默认的路径是/ftl,此时hello.ftl就是ftl下的文件
Template temp = cfg.getTemplate("helloHtml.ftl");
// 4、创建数据文件,非常类似于OGNL,使用map来进行设置
Map<String, Object> root = new HashMap<String, Object>();
root.put("username", "zll");
// 5、通过模板和数据文件生成相应的输出
temp.process(root, new FileWriter("d:/test/hello.html"));
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
4)、结果
三、小结
在JSP之前,用servelet写html页面怎么写?将html的标签作为整个输出流的一部分,不断的在servlet中拼写html的内容,然后嵌入相对应的数据内容,有了jsp之后,jsp对html标签和数据做了一个整合,而freemarker恰是在jsp之前,通过写好的html模板和数据,动态生成灵活页面。所以,如果没人拦着我,那么我觉得freemarker更像一个写好了html标签的servlet!!!有疑问么???
(下篇进行freemarker的封装)