最近項目中使用到了,對word模板進行編輯和渲染,所以使用到了模板引擎技術。
在項目中,我們前端使用的富文本編輯器,進行展示和保存(和word格式一致),后端采用了freemarker進行數據的渲染。前端,就不多說了,處理很簡單,只有一個展示,一個保存操作。
后台,需要獲取模板和數據,進行渲染后返回到前台,進行展示。
目前實現了輸入字符串和輸入文件兩種形式。(20180409)
freemark技術的整合和使用如下:
1.引入maven依賴
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
2.封裝為utils工具類使用
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.apache.log4j.PropertyConfigurator; import com.winning.Application; import com.winning.polaris.admin.service.impl.UpgradeServiceImpl; import com.winning.polaris.comm.util.LogUtil; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; public class FreemarkerUtils { private static LogUtil logger = LogUtil.getInstance(UpgradeServiceImpl.class); private static String defaultCharacter = "UTF-8"; private static Configuration cfg; private FreemarkerUtils() { } static { cfg = new Configuration(Configuration.getVersion()); cfg.setDefaultEncoding(defaultCharacter); cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX); } /** * 對模板進行渲染 * @param data 數據Map * @param tplStr 模板 * @return */ public static String generateString( Map<String, Object> data, String tplStr) { String result = null; String name="myStrTpl"; try { StringTemplateLoader stringTemplateLoader= new StringTemplateLoader(); stringTemplateLoader.putTemplate(name, tplStr); cfg.setTemplateLoader(stringTemplateLoader); Template template = cfg.getTemplate(name,defaultCharacter); StringWriter out = new StringWriter(); template.process(data, out); out.flush(); result= out.toString(); out.close(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 將模板渲染以后保存到文件 * @param templateFileDir 模板目錄 * @param fileName 模板文件名稱 * @param targetFilePath 渲染后文件名稱 * @param dataMap 數據 * @return */ public static boolean renderingTemplateAndGenerateFile(String templateFileDir, String fileName,String targetFilePath,Map<String, Object> dataMap){ boolean flag=true; try { // 設置文件所在目錄的路徑 cfg.setDirectoryForTemplateLoading(new File(templateFileDir));//模板路徑 // 獲取模版 Template template = cfg.getTemplate(fileName); // 設置輸出文件名,和保存路徑 File outFile = new File(targetFilePath); // 將模板和數據模型合並生成文件 重點設置編碼集 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")); // 生成文件 template.process(dataMap, out); // 關閉流 out.flush(); out.close(); } catch (Exception e) { logger.error("生產模板文件失敗!",e); flag=false; } return flag; } public static void main(String[] args) { PropertyConfigurator.configure(Application.class.getClassLoader().getResourceAsStream("config" + File.separator + "log4j.properties")); Map<String,Object> dataMap=new HashMap<String, Object>(); dataMap.put("APP_HOME", "c:/test/appHome"); //F:\freemark boolean renderingTemplateAndGenerateFile = renderingTemplateAndGenerateFile("F:\\freemark\\", "temp.txt", "F:\\freemark\\temp.bat",dataMap); System.out.println(renderingTemplateAndGenerateFile); } }
3.單元測試
public
class
FreemarkerUtilsTest
extends
TestCase {
public
void
generateStringTest(){
Map<String,Object> map=
new
HashMap<>();
map.put(
"date"
,
"2017-05-11 11:55:55"
);
map.put(
"caseNo"
,
"AJ00000001"
);
map.put(
"descrip"
,
"這是描述信息=========="
);
String template=
"案件編號為:${caseNo!} "
+
" 日期為:${date!} "
+
" 自動獲取日期為:${ .now?string('yyyy年MM月dd日')}"
+
"描述:${descrip!}"
;
String generateString = FreemarkerUtils.generateString(map, template);
System.out.println(
"------"
);
System.out.println(generateString);
}
}
|
結果:案件編號為:AJ00000001 日期為:2017-05-11 11:55:55 自動獲取日期為:2018年01月29日描述:這是描述信息==========
模板渲染完成。