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);
}
本文主要介绍了在Java中如何使用FreeMarker进行模板替换,通过一个简单的Demo展示了Maven依赖引入、帮助类编写以及测试类的实现过程。

4472

被折叠的 条评论
为什么被折叠?



