初识freemarker
2019-04-13 本文已影响0人
行走的鸡汤哥
1、添加依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2、freemarker基本使用
a、freemarker工具类
/**
* Created by r.x on 2019/4/13.
*/
public class FtlTool {
private FtlTool() {
}
public static StringWriter process(Map<String, Object> data) throws IOException, TemplateException {
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setClassLoaderForTemplateLoading(FtlTool.class.getClassLoader(), "ftl");
configuration.setDefaultEncoding("utf-8");
// 添加自定义函数
configuration.setSharedVariable(Score2GradeMethod.METHOD_NAME, new Score2GradeMethod());
Template template = configuration.getTemplate("test.ftl");
StringWriter writer = new StringWriter();
template.process(data, writer);
return writer;
}
}
b、自定义函数
/**
* Created by r.x on 2019/4/13.
*/
public class Score2GradeMethod implements TemplateMethodModelEx {
public static final String METHOD_NAME = "score2Grade";
@Override
public Object exec(List arguments) throws TemplateModelException {
if (arguments.get(0) instanceof SimpleNumber) {
SimpleNumber number = (SimpleNumber) arguments.get(0);
if (number.getAsNumber().doubleValue() > 80) {
return "优秀";
} else {
return "还行";
}
}
return null;
}
}
c、测试freemarker
/**
* Created by r.x on 2019/4/13.
*/
public class Demo {
public static void main(String[] args) throws IOException, TemplateException {
Map<String, Object> data = new HashMap<>();
data.put("id", "10086");
data.put("name", "张三");
data.put("age", 18);
data.put("salary", 12306.98765);
data.put("score", 90);
StringWriter stringWriter = FtlTool.process(data);
// 输出执行结果
System.out.println(stringWriter.toString());
stringWriter.flush();
stringWriter.close();
}
}
d、模板文件:test.ftl
"person_info": {
"id": "${id}",
"name": "${name}",
"age": ${age},
"salary": "${salary}",
"grade": "${score2Grade(score)}"
}
e、执行结果
"person_info": {
"id": "10086",
"name": "张三",
"age": 18,
"salary": "12,306.988",
"grade": "优秀"
}