java裏面我們需要使用模板的地方是比較多的,所以在freemarker官網查找資料整理了一個demo.
直接上代碼
maven依賴
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
編寫幫助類
package com.mqs.util;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.util.Map;
import java.io.StringWriter;
public class FreemarkerUtils {
private static String defaultCharacter = "UTF-8";
private static Configuration cfg;
private FreemarkerUtils() {
}
static {
cfg = new Configuration();
cfg.setDefaultEncoding(defaultCharacter);
cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
}
public static String processTemplate(String myTemplate, Map<String, Object> map){
String result = null;
String name = "template";
try {
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate(name, myTemplate);
cfg.setTemplateLoader(stringTemplateLoader);
Template template = cfg.getTemplate(name, defaultCharacter);
StringWriter out = new StringWriter();
template.process(map, out);
out.flush();
result = out.toString();
out.close();
} catch (Exception e){
e.printStackTrace();
}
return result;
}
}
測試類
public static void main(String[] args){
Map<String,Object> map= new HashMap<String, Object>();
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 result = FreemarkerUtils.processTemplate(template, map);
System.out.println(template);
System.out.println(result);
}