yml配置freemarker
freemarker:request-context-attribute: req #req访问requestsuffix: .ftl #后缀名content-type: text/htmlenabled: truecache: 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文件的工具类
/*** 封装freemarker用于创建模板和加载模板*/public class FreeMarkerUtil {private static final String htmlUrl = "C:\\Users\\ysx\\Desktop\\xxx\\";//生成静态html文件的位置private static final Version configVersion = Configuration.VERSION_2_3_28;//版本private static final Configuration config = new Configuration(configVersion);//单例private FreeMarkerUtil(){}/*** @param templateName 模板名字* @param root 模板根 用于在模板内输出结果集* @param indexFileName 输出对象 具体输出到哪里*/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");//生成文件(这里是我们是生成html)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();}}}/*** 初始化模板配置* @param templateDir 模板位置*/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);//根据模板生成静态html页面FreeMarkerUtil.processTemplate("/html/index2.ftl",root,"index2.html");return "forward:/static/index2.html";}