FreeMarker新手指南第一册

FreeMarker新手指南第一册

什么是freemarker

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。
FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
目前企业中:主要用Freemarker做静态页面或是页面展示

使用freemarker需要的jar
把下载到的jar包(freemarker-2.3.23.jar)放到\WebRoot\WEB-INF\lib目录下。
官方网站:http://freemarker.org/
如果使用的是Maven结构,可在pom.xml中引入以下坐标

Freemarker原理图

模板 + 数据模型 = 输出

应用例子

String dir = “C:\Users\lx\workspace-e\freemarker-java\“;
Configuration conf = new Configuration(Configuration.VERSION_2_3_23);
//加载模板文件(模板的路径)
conf.setDirectoryForTemplateLoading(new File(dir));
//配置默认字符集
configuration.setDefaultEncoding(“utf-8”);
// 加载模板
Template template = conf.getTemplate(“ftl/freemarker-demo.ftl”);
// 定义数据
Map root = new HashMap();
root.put(“world”, “世界你好”);
// 定义输出
Writer out = new FileWriter(dir + “ftl/freemarker.html”);
template.process(root, out);
out.flush();
out.close();
页面
${world}

Person p = new Person();
Map root = new HashMap();
root.put(“person”,p);
freemarker.html内容如下:
${person.id}=${person.name}

List persons = new ArrayList();
省略….
页面中内容
</#list persons as p>
${p.id}/${p.name}
<//#list>

List list = new ArrayList();
获取当前选代的索引:

</#list persons as p>
${p_index}
<//#list>

逻辑运算符(== != || &&)

输出一行字 index:${p_index}|${p.id}:${p.name}
index:${p_index}|${p.id}:${p.name}
index:${p_index}|${p.id}:${p.name}

默认格式
1:date
${cur_time?date}
2:datetime
${cur_time?datetime}
3:time
${cur_time?time}
自定义格式
${cur_time?string(“yyyy-MM-dd HH:mm:ss”)}

root.put(“val”,null);
解决办法
1:null 变 空串
${val!} ${val!”这里是空”}
2:为Null时给默认值
${val!“我是默认值”}
3:
</#if curdate ??>
属性不为空
</#else>
属性为空
</#/if>

将另一个页面引入本页面时可用以下命令完成
</#include “/include/head.html”>

freemaker整合spring

Configuration configuration = freeMarkerConfigurer.getConfiguration();
Template template = configuration.getTemplate(“item.ftl”);
Map root = new HashMap();
//取商品信息
….
FileWriter out = new FileWriter(new File(HTML_GEN_PATH + id + “.html”));
template.process(root, out);
out.flush();
out.close();


本作品采用知识共享署名 4.0 中国大陆许可协议进行许可,欢迎转载,但转载请注明来自御前提笔小书童,并保持转载后文章内容的完整。本人保留所有版权相关权利。

本文链接:https://royalscholar.cn/2017/11/27/FreeMarker新手指南第一册/

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×