经久不衰的优秀模板框架,对于固定的的静态页面都可以使用
初始化使用
- 引入jar包(推荐使用最新版)
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
2 创建使用类
public class FreemarkerUtil {
private static Configuration cfg;
public FreemarkerUtil() {
initFreemarker();
}
private void initFreemarker() {
cfg = new Configuration();
cfg.setClassForTemplateLoading(this.getClass(), "/");
cfg.setDefaultEncoding("UTF-8");
}
}
3 加载模板文件处理数据
//获取模板路径,后缀一般为ftl
Template template = cfg.getTemplate("ftl/"+ ftlName +".ftl");
Writer out= new OutputStreamWriter(new FileOutputStream(accountPath) , "UTF-8");
template.process(obj, out);}
//处理后数据 记得关闭流
// out.flush();
// out.close();
4 完整例子
FreemarkerUtil f = new FreemarkerUtil();
Configuration cfg = new Configuration();
cfg.setClassForTemplateLoading(f.getClass(),"/");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
/* Create a data-model */
Map root = new HashMap();
root.put("user", "Big Joe");
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
root.put("latestProduct", latest);
/* Get the template (uses cache internally) */
Template temp = cfg.getTemplate("ftl/template.ftl");
/* Merge data-model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
1.创建HTML模版
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
2.创建实体类
@Data
public class Product {
String url;
String name;
}
使用此注解配合lombok一起使用
3.运行main方法输出到控制台
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>