1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > freeMarker生成静态html页面

freeMarker生成静态html页面

时间:2022-12-08 04:43:03

相关推荐

freeMarker生成静态html页面

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";}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。