1,maven坐标
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2,模板文件,index.ftl
<html>
<head>
<meta charset="utf-8">
<title>Freemarker入门小DEMO </title>
</head>
<body>
<#--我只是一个注释,我不会有任何输出 -->
${name},你好。${message}<br/>
<#if success??>
你已通过实名认证
<#else>
你未通过实名认证
</#if>
</html>
3,java代码
pojo
public class Person {
private String name;
private String message;
private String success;
import com.freemark.pojo.Person;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
public class FreemarkMain {
public static void main(String[] args) throws IOException, TemplateException {
//1.创建配置类
Configuration configuration=new Configuration(Configuration.getVersion());
//2.设置模板所在的目录
configuration.setDirectoryForTemplateLoading(new File("src/main/resources/templates/"));
//3.设置字符集
configuration.setDefaultEncoding("utf-8");
//4.加载模板
Template template = configuration.getTemplate("index.ftl");
//5.创建数据模型
Person person = new Person();
person.setName("小苏");
person.setSuccess("");
person.setMessage(null);
//6.创建Writer对象
// Writer out =new FileWriter(new File("d:\\test.html"));
Writer out = new OutputStreamWriter(System.out);
//7.输出
template.process(person, out);
}
}
4,项目结构
来源:oschina
链接:https://my.oschina.net/u/3574106/blog/4299518