依赖
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
使用示例
package com.pengshiyu; import freemarker.template.Configuration; import freemarker.template.Template; import java.io.*; import java.util.HashMap; import java.util.Map; public class FreemarkerDemo { public static void main(String[] args) throws Exception { // 第一步:配置freemarker Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); // 设置模板路径 configuration.setDirectoryForTemplateLoading(new File("./")); // 第二步:加载模板 Template template = configuration.getTemplate("template.ftl"); // 第三步:模板数据 Map<String, Object> data = new HashMap<>(); data.put("name", "汤姆"); data.put("age", 23); // 第四步:渲染输出 // 输出到字符串 Writer stringWriter = new StringWriter(); template.process(data, stringWriter); stringWriter.close(); System.out.println(stringWriter.toString()); // 输出到文件 Writer fileWriter = new FileWriter(new File("hello.html")); template.process(data, fileWriter); fileWriter.close(); } }
模板文件 template.ftl
<html> <head> <title>Demo</title> </head> <body> <p>${name}</p> <p>${age}</p> </body> </html>
输出结果 hello.html
<html> <head> <title>Demo</title> </head> <body> <p>汤姆</p> <p>23</p> </body> </html>
问题及解决
报错
严重: DefaultObjectWrapper.incompatibleImprovements was set to the object returned by Configuration.getVersion(). That defeats the purpose of incompatibleImprovements, and makes upgrading FreeMarker a potentially breaking change. Also, this probably won't be allowed starting from 2.4.0. Instead, set incompatibleImprovements to the highest concrete version that's known to be compatible with your application.
解决方式
// 不推荐使用 Configuration configuration = new Configuration(Configuration.getVersion()); // 修改为: Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
模板语法
<#-- 注释 取出变量 --> Hello ${name} <#-- if判断--> <#if name == "Tom"> <span>is Tom</span> <#elseif name == "Jack"> <span>is Jack</span> <#else> <span>not is Tom</span> </#if> <#--for循环--> <#list list as item> <p>${item.name} ${item.age}</p> </#list> <#-- 引入模板 --> <#include "./footer.html">