学成在线--8.Freemarker入门教程
文章目錄
- 1.FreeMarker介紹
- 1)常用的java模板引擎還有哪些?
- 2)freemarker是一個用Java開發(fā)的模板引擎
- 3)模板+數(shù)據(jù)模型=輸出
- 2.FreeMarker快速入門
- 1)創(chuàng)建測試工程
- 2)配置文件
- 3)創(chuàng)建模型類
- 4)創(chuàng)建模板
- 5)創(chuàng)建controller
- 6)創(chuàng)建啟動類
- 7)測試
1.FreeMarker介紹
1)常用的java模板引擎還有哪些?
答:Jsp、Freemarker、Thymeleaf 、Velocity 等
2)freemarker是一個用Java開發(fā)的模板引擎
3)模板+數(shù)據(jù)模型=輸出
reemarker并不關(guān)心數(shù)據(jù)的來源,只是根據(jù)模板的內(nèi)容,將數(shù)據(jù)模型在模板中顯示并輸出文件(通常為html,也可以生成其它格式的文本文件)
例子:
數(shù)據(jù)模型:
模板:
輸出:
2.FreeMarker快速入門
1)創(chuàng)建測試工程
創(chuàng)建一個freemarker 的測試工程專門用于freemarker的功能測試與模板的測試。
pom.xml如下
2)配置文件
配置application.yml和 logback-spring.xml
從cms工程拷貝這兩個文件,進行更改, logback-spring.xml無需更改,application.yml內(nèi)容如下:
server: port: 8088 #服務(wù)端口 spring: application: name: test‐freemarker #指定服務(wù)名 freemarker: cache: false #關(guān)閉模板緩存,方便測試 settings: template_update_delay: 0 #檢查模板更新延遲時間,設(shè)置為0表示立即檢查,如果時間大于0會有緩存不方便 進行模板測試3)創(chuàng)建模型類
在freemarker的測試工程下創(chuàng)建模型類型用于測試
package com.xuecheng.test.freemarker.model; import lombok.Data; import lombok.ToString; import java.util.Date; import java.util.List; @Data @ToString public class Student { private String name;//姓名 private int age;//年齡 private Date birthday;//生日 private Float money;//錢包 private List<Student> friends;//朋友列表 private Student bestFriend;//最好的朋友 }4)創(chuàng)建模板
在 src/main/resources下創(chuàng)建templates,此目錄為freemarker的默認(rèn)模板存放目錄。
在templates下創(chuàng)建模板文件test1.ftl,模板中的${name}最終會被freemarker替換成具體的數(shù)據(jù)。
5)創(chuàng)建controller
創(chuàng)建Controller類,向Map中添加name,最后返回模板文件
package com.xuecheng.test.freemarker.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import java.util.Map; @RequestMapping("/freemarker") @Controller public class FreemarkerController { @Autowired RestTemplate restTemplate; @RequestMapping("/test1") public String freemarker(Map<String, Object> map){ map.put("name","黑馬程序員"); //返回模板文件名稱 return "test1"; } }6)創(chuàng)建啟動類
@SpringBootApplication public class FreemarkerTestApplication { public static void main(String[] args) { SpringApplication.run(FreemarkerTestApplication.class,args); } }7)測試
請求:http://localhost:8088/freemarker/test1
屏幕顯示:Hello 黑馬程序員!
總結(jié)
以上是生活随笔為你收集整理的学成在线--8.Freemarker入门教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Diango博客--8.解锁博客侧栏
- 下一篇: 编译ffmpeg安卓库(clang篇),