Freemarker生成代碼

FreeMarker簡介

FreeMarker 是一款 模板引擎,FreeMarker本身是一個模板,FreeMarker的思想是讓原本的一個頁面分成數據和模板,當我們更換數據和模板相加時可以生成不同的文本文件,包括HTML,java等。

所以學習FreeMarker主要是學習其中的一些標籤

簡單實例

0、引入jar包

 <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
 </dependency>

1、創建模板

package ${clsspath}

public interface ${daoName}Dao{

    public ${daoName} selectOne(${daoName} ${daoName});

    public List<${daoName}> selectAll(${daoName} ${daoName});

    public int insert(${daoName} ${daoName});

    public int update(${daoName} ${daoName});

}

其中的${}符號屬於佔位符,用於在寫入文件時寫入數據,模板文件後綴是ftl

2、編寫工具類

public void code() {
	Configuration configuration = new Configuration();
	
	// 這裏的數據用於插入模板中
	Map<String,Object> map = new HashMap<String, Object>();
	map.put("clsspath", "com.lihao.dao");
	map.put("daoName", "User");
	
	try {
		String path = this.getClass().getClassLoader().getResource("").getPath();
        //設置模板所在文件夾
        configuration.setDirectoryForTemplateLoading(new File(path));
        //模板文件所在位置
		Template t = configuration.getTemplate("Dao.ftl");
		//生成後代碼所在位置
		File docFile = new File("UserDao.java");
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
		t.process(map, out);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

public static void main(String[] args) {
	FreemarkerUtil f = new FreemarkerUtil();
	f.code();
}

運行main方法,執行代碼後會自動生成UserDao.java文件,生成代碼如下

package com.bdqn.dao

public interface UserDao{

    public User selectOne(User User);

    public List<User> selectAll(User User);

    public int insert(User User);

    public int update(User User);

}

3、後面的路

可以使用jdbc獲得數據庫中表結構,根據表名獲得數據自動生成項目中使用的service,dao,mapper的一些文件,減少自己勞動量,有興趣的同學可以自己試下

常見FreeMarker標籤

0、常規 =》 ${值名稱}

1、註釋 =》 <#–…–>

2、集合 =》
<#assign seq = [“winter”, “spring”, “summer”, “autumn”]>
<#list seq as x>
${s};
</#list>

3、分支 =》
<#if x == 1>
  x is 1
<#else>
  x is not 1
</#if>

4、分支2 =》
<#if x == 1>
  x is 1
<#elseif x == 2>
  x is 2
<#elseif x == 3>
  x is 3
</#if>

5、導入 =》
<#include “/common/copyright.ftl”>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章