yml配置freemarker
freemarker:
request-context-attribute: req
suffix: .ftl
content-type: text/html
enabled: true
cache: false
template-loader-path: classpath:/templates/
charset: UTF-8
settings:
number_format: '0.##'
创建ftl文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>freeMarker</title>
</head>
<body>
<ul>
<#list list as obj>
<li>${obj.peMeTitle}</li>
</#list>
</ul>
</body>
</html>
模板生成html文件的工具类
public class FreeMarkerUtil {
private static final String htmlUrl = "C:\\Users\\ysx\\Desktop\\xxx\\";
private static final Version configVersion = Configuration.VERSION_2_3_28;
private static final Configuration config = new Configuration(configVersion);
private FreeMarkerUtil(){}
public static void processTemplate(String templateName, Map<?,?> root, String indexFileName){
Writer out = null;
try{
out = new OutputStreamWriter(new FileOutputStream(htmlUrl+indexFileName),"UTF-8");
Template template=config.getTemplate(templateName,"utf-8");
template.process(root, out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}finally{
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void initConfig(String templateDir){
config.setLocale(Locale.CHINA);
config.setDefaultEncoding("utf-8");
config.setEncoding(Locale.CHINA, "utf-8");
config.setClassForTemplateLoading(FreeMarkerUtil.class,templateDir);
config.setObjectWrapper(new DefaultObjectWrapper(configVersion));
}
static {
initConfig("/templates");
}
}
调用工具类生成静态页面
@GetMapping("/freeMarker/html")
public String freeMarkerHtml() {
List<PermissionMenu> list = permissionMenuService.list();
Map<String, Object> root = new HashMap<>();
root.put("list",list);
FreeMarkerUtil.processTemplate("/html/index2.ftl",root,"index2.html");
return "forward:/static/index2.html";
}