資料+模闆 = 文本
常用的模闆技術:(1)freemarker 預設字尾 .ftl; (2)velocity 預設字尾 .vm
模闆技術的作用
(1)動态頁面靜态化(網站)
(2)代碼生成器
(3)郵件或者短信等的模闆
2.velocity(1)引入velocity jar包
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6</version>
</dependency>
(2)準備模闆 - hello.vm
## 我是一個沒有感情的注釋
${username},你好啊!!!
##對象資料擷取
##$!:有資料就顯示,沒有資料就不顯示(其它的沒有資料會直接顯示)
${employee.username} ====== ${employee.age}
$employee.username ====== $employee.age
$!employee.username ====== $!employee.age
##設定變量
#set($person = "接客")
$person
## 集合
#set($names=["湯母", "吉瑞", "肉絲"])
<p>$names.get(1)</p>
<ul>
#foreach($l in $names)
<li>$l</li>
#end
</ul>
(3) velocity的Java代碼
//測試預設就是項目根目錄
//資料 + 模闆 = 輸入文本
@Test
public void testHelloFile()throws Exception{
//建立一個Velocity引擎
VelocityEngine ve = new VelocityEngine();
//獲到到相應的模闆
Template template = ve.getTemplate("template/hello.vm","UTF-8");
//建立模闆上下文(裝資料的東西)
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("username","二狗");
//準備對象,放到上下文中
Employee employee = new Employee();
employee.setUsername("三狗");
// employee.setAge(45);
velocityContext.put("employee",employee);
//準備輸出的位置
FileWriter fileWriter = new FileWriter("template/hello.html");
//資料 + 模闆 = 輸入文本
template.merge(velocityContext, fileWriter);
fileWriter.close();
}
二.代碼生成器
1 EasyCodeEasyCode是基于IntelliJ IDEA開發的代碼生成插件,支援
自定義任意模闆(Java,html,js,xml)
EasyCode是基于IntelliJ IDEA Ultimate版開發的一個代碼生成插件,主要通過自定義模闆(基于velocity)來生成各種你想要的代碼。通常用于生成Entity(domain)、Dao、Service、Controller。如果你動手能力強還可以用于生成HTML、JS、PHP等代碼。理論上來說隻要是與資料有關的代碼都是可以生成的。
官方文檔 : https://gitee.com/makejava/EasyCode/wikis/pages?sort_id=725069&doc_id=166248
2 EasyCode 插件安裝![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yYwIDZkhTNzM2YxADOwQTOhFjYjhzMlVjY5ImZ2UTY38CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
(2)
模闆代碼的位置:(3)
生成時的路徑位置:檔案最終創關鍵的路勁為 Path+Package拼接起來