Freemarker使用入门

[quote]freemarker是一种模板标记工具,可以做页面静态化,代码生成 http://freemarker.sourceforge.net/[/quote]

1 pom 依赖

freemarker
freemarker
2.3.8
compile


2 工具类
public class FreemarkerUtil {
private static final Log logger = LogFactory.getLog(FreemarkerUtil.class.getName());

public static void generateContent(String templateFile, Map root, File destiFile){
try {
Configuration cfg = new Configuration();
cfg.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class, Constants.SLASH));
cfg.setObjectWrapper(new DefaultObjectWrapper());
Template temp = cfg.getTemplate(templateFile);
FileOutputStream outStream = new FileOutputStream(destiFile);
Writer out = new OutputStreamWriter(outStream);
temp.process(root, out);
out.flush();
} catch (Exception e) {
logger.error("", e);
}
}
}


3. 测试类
public class freemarkerTest {
@Test
public void testRender() {
Map root = new HashMap();
root.put("name", "wilson");
FreemarkerUtil.generateContent("test.ftl", root, new File("generatedFile"));
}
}


test.ftl
hello ${name}


输出文件
[quote]hello wilson[/quote]

4. freemarker eclipse高亮插件
http://www.jboss.org/tools/download/

你可能感兴趣的:(J2EE/Core,Java)