1 .引入freemarker包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version>
</dependency>
2 .准备freemarker模版 :模版名:xx.ftl
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${user.id}-----${user.name}-----${user.age}</h1>
<#if user.age lt 12>
${user.name}还是一个小孩
<#elseif user.age lt 18>
${user.name}快成年
<#else>
${user.name}已经成年
</#if>
</body>
</html>
新建一个templete文件夹或者包,将xx.ftl放到templete下。
新建的templete放到项目目录下:src/main/resources 或 src/main/java 目录下
都可以。
3 .map数据模型
Map<String,Object> root=new HashMap<String,Object>();
User user = new User();
user.setId(1011);
user.setName("汪峰");
user.setAge(52);
root.put("user", user);//在ftl中要赋值的变量
fu.fprint("03.ftl", root, "01.html");
4 .数据合并到模板
package artro.freeMarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreemarkerUtil {
public Template getTemplate(String name) {
try {
// 通过Freemarker的Configuration读取相应的ftl
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);// 这里是对应的你使用jar包的版本号
// 第二个参数 为你对应存放.ftl文件的包名
configuration.setClassForTemplateLoading(this.getClass(), "/templete");
Template template = configuration.getTemplate(name);
return template;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void print(String name, Map<String, Object> data) {
// 通过Template可以将模版文件输出到相应的文件流
Template template = this.getTemplate(name);
try {
template.process(data, new PrintWriter(System.out));// 在控制台输出内容
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 输出HTML文件
*
* @param name
* @param root
* @param outFile
*/
public void fprint(String name, Map<String, Object> data, String outFile) {
FileWriter out = null;
try {
// 通过一个文件输出流,就可以写到相应的文件中,此处用的是绝对路径
out = new FileWriter(new File("D:/new_works/freeMarker/src/static/"
+ outFile));
Template temp = this.getTemplate(name);
temp.process(data, out);
String str = out.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5 .常用的语法
1,通用插值:${expr};
2,数字格式化插值:#{expr}或#{expr;format}
3,循环读取集合:<#list student as stu>${stu}<br/></#list>