[java學習筆記]freemarker模板的頁面靜態化


  web開發中,對於動態頁面,可以采用web容器將數據和模板組裝成靜態頁面然后返回給前端的方式,但是這種方式的效率較低,因此,可以將一些變化不怎么頻繁的頁面,事先靜態化,作為靜態資源部署在nginx中,例如電商網站中的商品詳情頁面,在線教育系統中的課程詳情頁面等;這些靜態頁面的維護需要依靠一個后台管理系統,而這些后台管理系統生成靜態頁面的過程即為頁面靜態化;

  一個靜態頁面的生成需要兩個部分:模板和數據;模板技術有很多中,常見的有:jsp,freemarker,thymeleaf等。這里記錄一個使用freemarker模板生成靜態頁面的簡單程序:

@Test
    public void contextLoads() throws IOException, TemplateException {
        // 頁面靜態化測試,需要模板和數據;
        // 創建配置類
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 模板加載器,這是以字符串的形式加載模板,也可以設置模板路徑以文件的形式加載模板
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        // 模板字符串
        String templateStr = "<body>\n" +
                "姓名:${person.name}<br>\n" +
                "生日:${person.birthday?date}<br>\n" +
                "愛好:<#list person.hobbies as hobby>\n" +
                "    ${hobby}&nbsp;&nbsp;&nbsp;&nbsp;\n" +
                "</#list>\n" +
                "</body>";
        // 加載模板
        templateLoader.putTemplate("template", templateStr);
        configuration.setTemplateLoader(templateLoader);
        // 獲得模板
        Template template = configuration.getTemplate("template");

        // 准備數據
        Person person = new Person();
        person.setHobbies(new ArrayList<>());
        person.setBirthday(new Date());
        person.setName("測試姓名");
        person.getHobbies().add("song");
        person.getHobbies().add("jump");
        person.getHobbies().add("rap");
        person.getHobbies().add("busketball");
        Map<String, Object> map = new HashMap<>();
        map.put("person", person);

        // 靜態化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        // 輸出
        System.out.println(content);

        //
    }
View Code

生成的結果:

<body>
姓名:測試姓名<br>
生日:2019-7-16<br>
愛好:
    song&nbsp;&nbsp;&nbsp;&nbsp;

    jump&nbsp;&nbsp;&nbsp;&nbsp;

    rap&nbsp;&nbsp;&nbsp;&nbsp;

    busketball&nbsp;&nbsp;&nbsp;&nbsp;
</body>
View Code

然后再將這些生成的html放在本地的對應的文件夾,即可完成頁面的發布。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM