生活随笔
收集整理的这篇文章主要介绍了
Freemarker使用
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
添加jar包
<dependency><groupId>org.freemarker
</groupId><artifactId>freemarker
</artifactId><freemarker.version>2.3.23
</freemarker.version>
</dependency>
使用步骤
第一步:创建一个Configuration对象,直接new一个对象
构造方法的参数就是freemarker对于的版本号
第二步:设置模板文件所在的路径
第三步:设置模板文件使用的字符集。一般就是utf-8
第四步:加载一个模板,创建一个模板对象
第五步:创建一个模板使用的数据集
可以是pojo也可以是map,一般是Map
第六步:创建一个Writer对象
一般创建一FileWriter对象,指定生成的文件名
第七步:调用模板对象的process方法输出文件
第八步:关闭流
public class TestFreeMarker {@Test
public void testFreemarker() throws Exception {Configuration configuration
= new Configuration(Configuration
.getVersion());configuration
.setDirectoryForTemplateLoading(
new File(
"D:/workspaces-itcast/JavaEE28/taotao-item-web/src/main/webapp/WEB-INF/ftl"));configuration
.setDefaultEncoding(
"utf-8");
Template template
= configuration
.getTemplate(
"student.ftl");
Map data = new HashMap
<>();
data.put(
"hello",
"hello freemarker");Student student
= new Student(
1,
"小米",
11,
"北京昌平回龙观");
data.put(
"student", student);
List<Student
> stuList
= new ArrayList
<>();stuList
.add(
new Student(
1,
"小米",
11,
"北京昌平回龙观"));stuList
.add(
new Student(
2,
"小米2",
12,
"北京昌平回龙观"));stuList
.add(
new Student(
3,
"小米3",
13,
"北京昌平回龙观"));stuList
.add(
new Student(
4,
"小米4",
14,
"北京昌平回龙观"));stuList
.add(
new Student(
5,
"小米5",
15,
"北京昌平回龙观"));stuList
.add(
new Student(
6,
"小米6",
16,
"北京昌平回龙观"));stuList
.add(
new Student(
7,
"小米7",
17,
"北京昌平回龙观"));
data.put(
"stuList", stuList);
data.put(
"date",
new Date());
data.put(
"val",
"123456");Writer out
= new FileWriter(
new File(
"D:/temp/javaee28/out/student.html"));template
.process(
data, out);out
.close();}
}
语法格式
根据map中的key,获取数据
模板字段与key一致
${key}
总结
以上是生活随笔为你收集整理的Freemarker使用的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。