freeMarker生成静态html页面

yml配置freemarker

  freemarker:
    request-context-attribute: req  #req访问request
    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文件的工具类

/**
 * 封装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";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值