[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>
第五步,運行一下測試類,結果如下
需要你們的支持,纔是胖先生的動力,我會堅持!我的務實希望能讓你們有所收穫!