Freemarker是一个功能强大、灵活的模板引擎,用于生成动态内容,比如HTML、XML、JSON等。它可以作为一个独立的库,也可以集成到其他应用程序中。在Java应用程序中,我们可以使用Freemarker生成HTML网页、生成报表、生成邮件等。
下面是使用Freemarker的基本步骤:
1.引入Freemarker的依赖:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2.创建Configuration对象,并设置模板路径:
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
configuration.setClassForTemplateLoading(FreemarkerDemo.class, "/templates");
上面代码中,我们创建了一个Configuration对象,并设置模板路径为“/templates”(在你的项目中需要根据实际情况修改)。
3.获取Template对象:
Template template = configuration.getTemplate("hello.ftl");
上面代码中,我们获取了名为“hello.ftl”的模板文件。
4.创建数据模型:
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("name", "John");
dataModel.put("age", 25);
上面代码中,我们创建了一个Map对象,用于存储模板中需要的数据。
5.渲染模板:
StringWriter stringWriter = new StringWriter();
template.process(dataModel, stringWriter);
String output = stringWriter.toString();
上面代码中,我们使用Template对象的process方法来渲染模板。process方法需要传入数据模型和一个Writer对象,它会将渲染结果写入Writer中。最后我们可以将字符串形式的渲染结果输出或保存到文件中。
下面是一个完整的例子:
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class FreemarkerDemo {
public static void main(String[] args) throws Exception {
// 创建Configuration对象,并设置模板路径
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
configuration.setClassForTemplateLoading(FreemarkerDemo.class, "/templates");
// 获取Template对象
Template template = configuration.getTemplate("hello.ftl");
// 创建数据模型
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("name", "John");
dataModel.put("age", 25);
// 渲染模板
StringWriter stringWriter = new StringWriter();
template.process(dataModel, stringWriter);
String output = stringWriter.toString();
// 输出结果
System.out.println(output);
// 保存结果到文件
try (FileWriter fileWriter = new FileWriter(new File("output.html"))) {
fileWriter.write(output);
}
}
}
上面代码中,我们使用了“hello.ftl”模板文件来生成HTML网页,模板文件内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<h1>Hello ${name}!</h1>
<p>You are ${age} years old.</p>
</body>
</html>
使用Freemarker的时候,我们可以在模板中使用表达式、指令、变量等。下面是一些常用的语法:
1.表达式
使用${}包含的表达式,可以在模板中输出变量和运算结果。
例如:
<h1>${name}</h1>
<p>${a + b}</p>
2.指令
使用<#>包含的指令,可以控制模板的流程。
例如:
<#if age > 18>
<p>You are an adult.</p>
<#else>
<p>You are a child.</p>
</#if>
3.变量
使用#{}包含的变量,可以在模板中定义变量或调用方法。
例如:
<#assign sum = a + b>
<p>The sum is ${sum}.</p>
<#function add(a, b)>
<#return a + b>
</#function>
<p>The result is ${add(a, b)}.</p>
以上就是使用Freemarker的基本步骤和语法介绍。使用Freemarker可以帮助我们更方便、快捷地生成动态内容,提高开发效率。