[freemarker篇]02.生成HTML的静态页面

昨天完成了一部分的今天在上次的基础上,完成完成生成HTML静态页面的操作,中间会涉及一点标签的简单使用。今天的代码有一丢丢的对付的感觉!抱歉了,直接就上代码吧!求原谅!

项目结构目录如下:

第一步,新建一个类com.shxt.model.User

package com.shxt.model;

public class User {
    
    private String account;
    private Integer age;
    
    public User() {
    }
    public User(String account, Integer age) {
        this.account = account;
        this.age = age;
    }


    public String getAccount() {
        return account;
    }
    public void setAccount(String account) {
        this.account = account;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    
    

}

第二步,在FreemarkerUtils中新建一个方法,这个方法就不过多的介绍了,很简单的!

/**
     * 到处HTML静态文件
     * @param name
     * @param root
     * @param outFile
     */
    public void exportHtml(String name,Map<String, Object> root,String outFile){
        FileWriter out = null;
        try {
            out = new FileWriter("D:\temp\"+outFile);
            //通过Template可以将模版文件输出到相应的文件流
            Template template = this.getTemplate(name);
            template.process(root, out);//在控制台输出内容
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(out!=null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        
    }

这里需要注意的是,我目前的输出地址为绝对路径,这里只是学习使用

第三步,测试数据项

@Test
    public void exportHtml() {
        // 1.创建数据模型
        Map<String, Object> root = new HashMap<String, Object>();
        // 2.赋值
        root.put("user_name", "胖先生");
        //传递数据之一个对象
        root.put("user", new User("四胖子",18));
        //传递一个结合显示
        List<User> userList = Arrays.asList(new User("1号胖子",19),new User("2号胖子",30),new User("3号胖子",50));
        root.put("userList", userList);
        // 3.生成HTML文件
        fu.exportHtml("demo02.ftl", root, "哈哈.html");
    }

第四步,建立ftl包下建立demo02.ftl文件,代码如下

<!DOCTYPE html>
<html>
  <head>
    <title>生成静态的HTML代码</title>
   <meta charset="UTF-8"> 
  </head>
  
  <body>
    <h1>你好:${user_name}</h1>
<hr/>
<h2>对象数据:${user.account}----${user.age}</h2> <#if user.age lt 17> 你为成年 <#else>你成年了 </#if>
<hr/>

<h2>遍历数据</h2> <#list userList as user> <#-- 我是注释:如何现实行号 --> ${user_index+1} ---- ${user.account}----${user.age} <#if !user_has_next> 共有${userList?size}最后一个用户是:${user.account} </#if> <br/> </#list> </body> </html>

第五步,运行一下测试类,结果如下

需要你们的支持,才是胖先生的动力,我会坚持!我的务实希望能让你们有所收获

原文地址:https://www.cnblogs.com/pangxiansheng/p/4778505.html