一、什么是freemarker?
freemarker是一种动态模板语言,它基于动态的数据加上模板生成html。freemarker本身就是一个java的类库,而不是最终向用户展示的。freemarker的原理是:模板+数据模型=输出
二、freemarker版本的hello world
第一步:引入jar包:http://www.freemarker.cn/archives/183.html
第二步:编写模板文件hello.ftl
<#ftl attributes={"content_type":"text/html; charset=UTF-8"}>
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${hello}!
</body>
</html>
第三步:编写数据模型
public class TestFreemarker {
public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("E:/ftl"));
Template template = cfg.getTemplate("hello.ftl");
Map<String, Object> map = new HashMap<String, Object>();
map.put("hello", "Hello FreeMarker!");
StringWriter stringWriter = new StringWriter();
template.process(map, stringWriter);
String resultStr = stringWriter.toString();
System.out.println(resultStr);
}
}
结果:
?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
Hello FreeMarker!
</body>
</html>