欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Freemarker使用

发布时间:2025/3/20 编程问答 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Freemarker使用 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

添加jar包

<!-- freemarker --> <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 {@Testpublic void testFreemarker() throws Exception {//1.创建一个模板文件//2.创建一个Configuration对象Configuration configuration = new Configuration(Configuration.getVersion());//3.设置模板所在的路径configuration.setDirectoryForTemplateLoading(new File("D:/workspaces-itcast/JavaEE28/taotao-item-web/src/main/webapp/WEB-INF/ftl"));//4.设置模板的字符集,一般utf-8configuration.setDefaultEncoding("utf-8");//5.使用Configuration对象加载一个模板文件,需要指定模板文件的文件名。 // Template template = configuration.getTemplate("hello.ftl");Template template = configuration.getTemplate("student.ftl");//6.创建一个数据集,可以是pojo也可以是map,推荐使用mapMap 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");//7.创建一个Writer对象,指定输出文件的路径及文件名。Writer out = new FileWriter(new File("D:/temp/javaee28/out/student.html"));//8.使用模板对象的process方法输出文件。template.process(data, out);//9.关闭流out.close();} }

语法格式

根据map中的key,获取数据
模板字段与key一致
${key}

总结

以上是生活随笔为你收集整理的Freemarker使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。