首先是下载freemarker的jar包:下载地址
写标签类(需要继承TemplateDirectiveModel接口重写execute方法)
package freemarker; import java.io.IOException; import java.io.Writer; import java.util.Map; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateNumberModel; public class LabelDirective implements TemplateDirectiveModel { @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Writer out = env.getOut(); //将模版里的数字参数转化成int类型的方法,,其它类型的转换请看freemarker文档 TemplateModel paramValue = (TemplateModel) params.get("num"); int num = ((TemplateNumberModel) paramValue).getAsNumber().intValue(); out.write("Akishimo num=" + params.get("num")+"的类型为:"+paramValue.getClass()); if (body != null) { body.render(env.getOut()); }else{ throw new RuntimeException("标签内部至少要加一个空格"); } } }
写配置和测试的类:
1 package freemarker; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileOutputStream; 6 import java.io.OutputStreamWriter; 7 import java.io.Writer; 8 import java.util.HashMap; 9 import java.util.Map; 10 11 import freemarker.template.Configuration; 12 import freemarker.template.DefaultObjectWrapper; 13 import freemarker.template.Template; 14 15 public class Test { 16 17 public static void main(String[] args) throws Exception { 18 19 Configuration cfg = new Configuration(); 20 //将写好的标签加入,起名叫label 21 cfg.setSharedVariable("label", new LabelDirective()); 22 cfg.setDirectoryForTemplateLoading(new File("temp")); 23 cfg.setObjectWrapper(new DefaultObjectWrapper()); 24 25 Template temp = cfg.getTemplate("list.ftl"); 26 27 Map root = new HashMap(); 28 root.put("user", "rzy"); 29 30 /* Writer out = new OutputStreamWriter(System.out); */ 31 32 File htmlFile = new File("E:/a.html"); 33 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8")); 34 35 temp.process(root, out); 36 out.flush(); 37 } 38 }
模版list.ftl先这么写
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <h1>${user}自定义标签输出结果</h1><br/> <@label num=12> </@label> </body> </html>
运行后打开e盘里面生成的a.html结果为: